<?php
            
use app\model\Record; 
use app\model\Common; 
use app\model\Ad; 
use app\model\Comm; 
use app\model\Theme; 
use app\model\Sms; 
use app\model\Poster; 
use app\model\Fans; 
use app\model\Userdata; 


/**
 * Desc:
 * Time: 2021/3/11 7:47 下午
 */
require_once PATH_MODULE .'define.php';
class LotteryModel extends PluginModel {

    public static function getPrizeList($themeid,$title='',$type='',$status=0,$default_type=0,$page_start=0,$page_size=10)
    {
        $condition = "";
        if ($title) {
            $condition .= " and title='".$title."'";
        }
        if ($type) {
            $condition .= " and type='".$type."'";
        }
        if ($status<0){
            $condition .= " and status!=2";
        }else if ($status>0){
            $condition .= " and status=$status";
        }

        if ($default_type && $default_type!='status') {
            $condition .= " and default_type='".$default_type."'";
        }
        $condition .= " order by status asc, show_sort asc";
        if ($page_size){
            $condition .= "  limit ".$page_start.",".$page_size;
        }
        $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid".$condition;
        return db_select($sql);
    }

    public static function getPrizeAll($themeid,$is_show=false)
    {
        if ($is_show){
            $res = db_getall(yx_lt_prize,['themeid'=>$themeid,'status'=>1]);
        }else{
            $res = db_getall(yx_lt_prize,['themeid'=>$themeid]);
        }

        return $res;
    }

    public static function getMaxQtyAndPrPrice($themeid)
    {
        $sql = " select * from ".tablename(yx_lt_prize)." where themeid=$themeid and pr >0 and qty>0 and type='default' and status=2 ";
        return db_find($sql);
    }

    public static function getDoublePrizeCount($themeid)
    {
        $sql = " select count(*) as cnt from ".tablename(yx_lt_prize)." where themeid=$themeid and is_double=1";
        return intval(db_find($sql)['cnt']);
    }

    public static function getPrizeFlagCount($themeid,$is_show=false)
    {
        $prize_list = [
            ['title'=>'全部','total'=>0,'p_id'=>0]
        ];
        $res = self::getPrizeAll($themeid,$is_show);
        $sort = array_column($res, 'show_pr');
        array_multisort($sort, SORT_ASC, $res);
        foreach ($res as $key => $val){
            $temp = ['title'=>$val['title'],'total'=>0,'p_id'=>$val['p_id']];
            array_push($prize_list,$temp);
        }
        foreach ($prize_list as $key => $val){
            if ($val['title']=='全部'){
                $sql = "select count(*) as cnt from " . tablename(yx_lt_flag)." where  themeid=".$themeid ." and status != -1";
                $prize_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }else{
                $p_id = $val['p_id'];
                $sql = "select count(*) as cnt from " . tablename(yx_lt_flag)." where p_id=$p_id and  themeid=".$themeid." and status != -1";
                $prize_list[$key]['total'] = intval(db_find($sql)['cnt']);
            }
        }
        return $prize_list;
    }

    //获取用户中奖记录数
    public static function getUserFlags($themeid,$uid,$status=0)
    {
        if (empty($uid)){
            return ;
        }
        $last_sql = '';
        if ($status){
            $last_sql = " and status=$status ";
        }
        $sql = " select count(*) as cnt from ".tablename(yx_lt_flag)." where themeid=$themeid and uid='".$uid."'".$last_sql;
        return intval(db_find($sql)['cnt']);
    }


    //获取用户的抽奖记录数
    public static function getUserSystemChance($themeid,$uid)
    {
        $sql = " select count(*) as cnt from ".tablename(yx_lt_chance)." where themeid=$themeid and uid='".$uid."' and type='system' and chance<0";
        return intval(db_find($sql)['cnt']);
    }
    //删除用户抽奖机会记录
    public static function deleteChanceFlag($where)
    {
        return db_delete(yx_lt_chance,$where);
    }

    public static function getFlagTypeCount($themeid)
    {
        $type_list = [
            ['title'=>'全部','status'=>0],
            ['title'=>'已兑换其他，当前失效','status'=>2],
            ['title'=>'未核销','status'=>3],
            ['title'=>'已核销','status'=>4],
            ['title'=>'虚拟记录','status'=>-1],
        ];
        foreach ($type_list as $key =>$val){
            $status = $val['status'];
            if ($status==0){
                $sql = "select count(*) as cnt from " . tablename(yx_lt_flag)." where status>-1 and themeid=".$themeid;
            }else{
                if ($status==1 || $status==3){
                    $sql = "select count(*) as cnt from " . tablename(yx_lt_flag)." where status=1 or status=3 and  themeid=".$themeid;
                }else{
                    $sql = "select count(*) as cnt from " . tablename(yx_lt_flag)." where status=$status and  themeid=".$themeid;
                }

            }
            $type_list[$key]['total'] =  intval(db_find($sql)['cnt']);
        }
        return $type_list;
    }


    //计算中奖概率、展示概率是不是百分值百
    public static function getPrTotal($list,$type='pr',$default_type='all')
    {
        if (is_array($list)){
            $temp_total_pr = 0;
            foreach ($list as $k => $v){
                if ($type=='pr'){
                    if ($default_type=='bizhong'){
                        if ($v['default_type']==3){
                            $temp_total_pr += intval($v['pr']);
                        }
                    }elseif ($default_type=='notbizhong'){
                        if ($v['default_type']!=3){
                            $temp_total_pr += intval($v['pr']);
                        }
                    }else{
                        $temp_total_pr += intval($v['pr']);
                    }
                }
                if ($type=='show_pr'){
                    $temp_total_pr += intval($v['show_pr']);
                }
            }
            return $temp_total_pr;
        }
        return 0;
    }

    /**
     * Desc:获取奖品每日发放数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/18 2:15 下午
     * @param $list
     * @return int
     */
    public static function getDayOut($list)
    {
        if (is_array($list)){
            $temp_total_day_out = 0;
            foreach ($list as $k => $v){
                $temp_total_day_out += intval($v['day_qty']);
            }
            return $temp_total_day_out;
        }
        return 0;
    }

    //插入奖项
    public static function insertPrize($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = $insertid = db_insert(yx_lt_prize,$data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }
    //修改奖项
    public static function editPrizeItemByWhere($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(yx_lt_prize,$data,$where);
        if (!empty($res)) {
            return true;
        } else {
            return false;
        }
    }
    //获取奖项
    public static function getPrizeItemById($id,$themeid)
    {
        $res = db_get(yx_lt_prize,['p_id'=>$id,'themeid'=>$themeid]);
        return $res;
    }
    //搜索奖项
    public static function searchPrize($themeid,$question,$page_start,$page_size)
    {
        $condition="";
        if (!empty($question)) {
            $condition .= " AND name LIKE '%".$question."%'"." OR title like '%".$question."%'";
        }
        $condition .= " GROUP BY p_id ORDER BY created_at DESC  ";
        if ($page_size) {
            $condition .= " LIMIT " .$page_start.",".$page_size;
        }
        $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid".$condition;
        return db_select($sql);
    }

    //删除奖项
    public static function deletePrize($p_id,$themeid)
    {
         return db_delete(yx_lt_prize,['p_id'=>$p_id,'themeid'=>$themeid]);
    }

    /**
     * Desc:获取用户的抽奖机会记录次数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/28 3:16 下午
     * @param $uid  -用户uid
     * @param $themeid -活动id
     * @return int
     */
    public static function getUserChanceByUidAndThemeId($uid,$themeid)
    {
        $sql = "select count(*) as cnt from " . tablename(yx_lt_chance)." where uid='".$uid."' and themeid=".$themeid;
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:获取用户第一次抽奖时间
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/8/30 9:03 上午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserFirstChanceByWhere($themeid,$uid)
    {
        $sql = "select created_at,admin_name from " . tablename(yx_lt_chance)." where uid='".$uid."' and themeid=".$themeid." and chance<0 and type='system' order by created_at asc";
        return db_find($sql);
    }

    //获取抽奖机会使用记录
    public static function getChanceList($themeid,$type='',$uid=0,$chance=0,$page_start=0,$page_size=0,$search='',$start_day='',$end_day='',$count = false)
    {
        $condition = "";
        if ($uid) {
            $condition .= " AND a.uid='{$uid}'";
        }
        if ($type) {
            $condition .= " AND a.type='".$type."'";
        }
        if ($chance) {
            $condition .= " AND a.chance=$chance";
        }
        if ($search){
            $condition .= " and b.nickname like '".$search."'"." or b.mobile like '".$search."' " ." or b.username like '".$search."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        $condition .= " ORDER BY a.created_at DESC ";
        if ($page_size && !$count) {
            $condition .= " LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(yx_lt_chance)." AS a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(t_fans)." AS c ON a.from_uid=c.uid and c.themeid=$themeid".
            " WHERE a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.*,b.id as fan_id,b.avatar,b.nickname,b.username,b.mobile,b.jihui,c.nickname as from_nickname,c.avatar as from_avatar,c.uid as from_uid ".$sql;
            return db_select($sql);
        }

    }

    /**
     * Desc:获取没有使用抽奖机会的用户
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/21 8:58 上午
     * @param $themeid
     * @param int $page_start
     * @param int $page_size
     * @param string $search
     * @param string $start_day
     * @param string $end_day
     * @return array
     */
    public static function getNoUsedUserList($themeid,$page_start=0,$page_size=0,$search='',$count = false)
    {
        $sql1 = "select uid from ".tablename(yx_lt_chance)." where chance >0 and themeid=$themeid group by uid";
        $res1 = db_select($sql1);
        $sql2 = "select uid from ".tablename(yx_lt_chance). " where chance =-1 and themeid=$themeid group by uid";
        $res2 = db_select($sql2);
        $add_arr = [];
        $used_arr = [];
        $diff_arr = [];
        foreach ($res1 as $key => $val){
            array_push($add_arr,$val['uid']);
        }
        foreach ($res2 as $k => $v){
            array_push($used_arr,$v['uid']);
        }
        $diff_arr = array_diff($add_arr,$used_arr);
        if (!$diff_arr){
            if ($count){
                return 0;
            }
            return [];
        }else{
            $diff_uid = '';
            foreach ($diff_arr as $kk => $vv){
                $diff_uid .= $vv.',';
            }
            $diff_uid = '('.rtrim($diff_uid,',').')';
            $condition = "";
            if ($search){
                $condition .= " and a.nickname like '".$search."'"." or a.mobile like '".$search."' " ." or a.username like '".$search."' ";
            }
            $condition .= " group by b.uid";
            if ($page_size && !$count) {
                $condition .= " LIMIT ".$page_start.",".$page_size;
            }
            $sql = "  from ".tablename(t_fans)." as a ".
                "left join ".tablename(yx_lt_chance)." as b on a.uid=b.uid and b.themeid=$themeid".
                " where a.themeid=$themeid and a.uid in $diff_uid ".$condition;
            if ($count){
                return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
            }else{
                $sql = " select a.uid,a.nickname,a.avatar,a.username,a.mobile,a.jihui ".$sql;
                return db_select($sql);
            }

        }

    }

    public static function getUserHasChanceList($themeid,$uid=0,$chance=0,$page_start=0,$page_size=0,$search='',$start_day='',$end_day='')
    {
        $condition = "";
        if ($uid) {
            $condition .= " AND a.uid='{$uid}'";
        }
        if ($chance) {
            $condition .= " AND a.chance=$chance";
        }
        if ($search){
            $condition .= " and b.nickname like '".$search."'"." or b.mobile like '".$search."' " ." or b.username like '".$search."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        $condition .= " ORDER BY a.created_at DESC ";
        if ($page_size) {
            $condition .= " LIMIT ".$page_start.",".$page_size;
        }
        $sql = " SELECT a.*,b.id as fan_id,b.avatar,b.nickname,b.username,b.mobile,b.jihui FROM ".tablename(yx_lt_chance)." AS a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " WHERE a.themeid=$themeid".$condition;
//        var_dump($sql);die();
        return db_select($sql);
    }

    public static function getStatesList()
    {

    }

    public static function getStatesTypeTotal()
    {
        $temp_arr = [
            ['title'=>'全部','total'=>0,'status'=>0],
            ['title'=>'已抽','total'=>0,'status'=>1],
            ['title'=>'未抽','total'=>0,'status'=>2],
        ];
        foreach ($temp_arr as $key => $val){

        }
    }

    //搜索用户的抽奖机会使用记录
    public static function searchChance($themeid,$search,$page_start,$page_size)
    {
        $condition="";
        if (!empty($search)) {
            if (CheckPhoneNumber($search)) {
                $condition .= " AND b.mobile='".$search."'";
            } else {
                $condition .= " AND b.username LIKE '%".$search."%'";
            }

        }
        $condition .= " ORDER BY a.created_at DESC  ";
        if ($page_size) {
            $condition .= " LIMIT " .$page_start.",".$page_size;
        }
        $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile FROM ".tablename(yx_lt_chance)." AS a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON b.themeid=$themeid".
            " WHERE a.themeid=$themeid".$condition;
        return db_select($sql);
    }
    //获取实物奖项中奖记录
    public static function getDefaultLtList($themeid,$status=0,$p_id=0,$page_start=0,$page_size=10,$uid=0,$is_fix=false,$count = false)
    {
        $condition = "";
        if ($p_id){
            $condition .= " AND a.p_id=$p_id";
        }
        if ($status) {
            if ($is_fix && ($status==1 || $status==3)){
                $condition .= " AND a.status=1 or a.status=3";
            }else{
                $condition .= " AND a.status=$status";
            }
        }else{
            $condition .= " AND a.status > -1";
        }
        if ($uid){
            $condition .= " AND a.uid='{$uid}'";
        }
        $condition .= " ORDER BY a.created_at DESC ";
        if ($page_size && !$count) {
            $condition .= " LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(yx_lt_flag)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(yx_lt_prize)." AS c ON a.p_id=c.p_id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_2019fans)." AS d ON a.uid=d.id ".
            " LEFT JOIN ".tablename(t_record)." AS f ON a.uid=f.uid and a.themeid=$themeid".
            " WHERE a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,c.name,c.title,c.small_img,c.default_type,c.red_envelopes_amount_min,c.red_envelopes_amount_max,
        d.username as xn_username,d.nickname as xn_nickname,d.avatar as xn_avatar,d.mobile as xn_mobile,f.status as pay_status ".$sql;
            return db_select($sql);
        }

    }



    //搜索获取中奖的记录
    public static function searchDefaultLt($themeid,$search='',$page_start=0,$page_size=10,$start_day='',$end_day='',$is_group=false,$count = false)
    {
        $condition="";
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or a.convert_code LIKE '".$search."' "." or b.username LIKE '".$search."'";
        }
        if ($start_day && $end_day && $start_day!=$end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        if ($is_group){
            $condition .= " group by a.uid";
        }
        $condition .= " and a.status > -1";
        $condition .= " ORDER BY a.created_at DESC ";

        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(yx_lt_flag)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(yx_lt_prize)." AS c ON a.p_id=c.p_id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_record)." AS f ON a.uid=f.uid and f.themeid=$themeid".
            " WHERE a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,c.name,c.title,c.small_img,c.default_type,c.red_envelopes_amount_min,c.red_envelopes_amount_max,f.status as pay_status ".$sql;
            return db_select($sql);
        }

    }
    //获取指定的中奖记录信息
    public static function getLtFlagItem($themeid,$uid,$f_id)
    {
        if (empty($uid)){
            return ;
        }
        $res = db_get(yx_lt_flag,['f_id'=>$f_id,'themeid'=>$themeid,'uid'=>$uid]);
        return $res;
    }

    public static function getLtFlagItemByWhere($where)
    {
        $res = db_get(yx_lt_flag,$where);
        return $res;
    }
    //修改中奖记录
    public static function editLtFlagItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $data['checked_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(yx_lt_flag,$data,$where);
        if (!empty($res)) {
            return true;
        } else {
            return false;
        }
    }

    public static function editLtFlagItemByWhere($f_id,$themeid,$uid,$workerid)
    {
        if (empty($uid)){
            return ;
        }
        $updated_at = date("Y-m-d H:i:s",time());
        $checked_at = date("Y-m-d H:i:s",time());
        $sql = " update ".tablename(yx_lt_flag)." set status=4 , workerid=$workerid, updated_at='".$updated_at."' ,checked_at='".$checked_at."' where  (f_id=$f_id and themeid=$themeid and uid='{$uid}') and (status=1 or status=3) ";
        return \think\Db::execute($sql);
    }

    //插入中奖记录
    public static function insertLtFlag($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = $insertid = db_insert(yx_lt_flag,$data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }
    //获取红包获得记录
    public static function getRedPackageList($themeid,$status=0,$page_start=0,$page_size=10,$count = false)
    {
        $condition = "";
        if ($status) {
            $condition .= " AND a.status=$status";
        }
        $condition .= " ORDER BY a.created_at DESC  ";
        if ($page_size && !$count) {
            $condition .= " LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(yx_lt_rp_flag)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b on a.uid=b.uid and b.themeid=$themeid".
            " WHERE a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile ".$sql;
            return db_select($sql);
        }

    }
    //搜索红包记录
    public static function searchRedPackage($themeid,$search,$page_start=0,$page_size=10,$start_day,$end_day,$count = false)
    {
        $condition="";
        if ($search){
            $condition .= " AND b.nickname LIKE '".$search."'"." or b.mobile LIKE '".$search."' "." or a.convert_code LIKE '".$search."' ";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
        }
        $condition .= " ORDER BY a.created_at DESC ";
        if ($page_size && !$count) {
            $condition.= "LIMIT ".$page_start.",".$page_size;
        }
        $sql = "  FROM ".tablename(yx_lt_rp_flag)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b on a.uid=b.uid and b.themeid".
            " WHERE a.themeid=$themeid".$condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile ".$sql;
            return db_select($sql);
        }

    }
    //插入机会使用记录
    public static function insertChance($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = $insertid = db_insert(yx_lt_chance,$data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }

    /**
     * Desc: 获取用户的抽剩余奖机会
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/8/23 6:14 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserUsedChance($config,$fans,$themeid,$uid)
    {
        $sql = " select count(*) as cnt from ".tablename(yx_lt_chance)." where themeid=$themeid and uid='{$uid}' and chance<0 and type='system'";
        $used_lag_total = db_find($sql)['cnt'];
        $tempa = $fans['jihui']+$used_lag_total;
        if ($tempa>$config['yx_lt_chance_limit']){
            $remain_num = max(0,($config['yx_lt_chance_limit']-$used_lag_total));
        }else{
            $remain_num = $fans['jihui'];
        }
        return  $remain_num;
    }

    /**
     * Desc:获取用户使用的的抽奖次数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/8/31 9:20 上午
     * @return mixed
     */
    public static function getUserChanceUsed($themeid,$uid)
    {
        $sql = " select count(*) as cnt from ".tablename(yx_lt_chance)." where themeid=$themeid and uid='{$uid}' and chance<0 and type='system'";
        $used_lag_total = db_find($sql)['cnt'];
        return $used_lag_total;
    }
    //修改抽奖机会
    public static function editChance($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(yx_lt_chance,$data,$where);
        if (!empty($res)) {
            return true;
        } else {
            return false;
        }
    }
    //插入红包领取记录
    public static function insertRpFlag($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = $insertid = db_insert(yx_lt_rp_flag,$data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }

    //获取红包记录
    public static function getRpFlagItem($where)
    {
        return db_get(yx_lt_rp_flag,$where);
    }

    /**
     * Desc:更新红包领取记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/7/27 2:29 下午
     * @param $where
     * @param $data
     * @return false
     */
    public static function updateRpFlag($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(yx_lt_rp_flag,$data,$where);
        if (!empty($res)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Desc:查询定时记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/30 1:17 下午
     * @param $where
     * @return mixed
     */
    public static function getTimeSetFlagItem($where)
    {
        return db_get(yx_lt_timeset,$where);
    }
    //插入定时记录
    public static function insertTimeSetItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = $insertid = db_insert(yx_lt_timeset,$data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }
    //修改定时记录
    public static function editTimeSetItem($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(yx_lt_timeset,$data,$where);
        if (!empty($res)) {
            return true;
        } else {
            return false;
        }
    }


    //抽奖首页
    public static function indexMethod($theme,$config,$uid,$fromuid,$has_order)
    {
//        if (empty($uid)){
//            return ;
//        }
        try {
            $themeid = $theme['id'];
            $top_img = isset($config['yx_lt_top_img'])?$config['yx_lt_top_img']:'';
            //判断是否更新抽奖奖品组 注释16个奖品切换逻辑
            //self::setTimeChangePrizeGroupStatus($themeid);
            if ($uid){
                $error_txt = self::checkBaseError($theme);
                self::initInfo($themeid,$config,$uid,$fromuid);//抽奖的初始化、判断幸运星、好友到访
                $method_list = self::getLotteryMethod($uid,$themeid,$config,$has_order,true);//抽奖攻略 为了定时任务自动增加抽奖机会和插入新定时领取
                $fans = self::getUserInfoById($uid,$themeid);
                $lt_btn_txt = '开始抽奖';
                $remain_num = 0;
                $tips = '';
                $can_lt = false;
                $show_no_chance_num = $fans['show_modal_num'];
                $remain_num = self::getUserUsedChance($config,$fans,$themeid,$uid);

                //自动修正 用户抽奖机会
                if ($fans['jihui']>0){
                    $debug_used_chance = self::getUserRecordsByType($fans['uid'],'used',$themeid,false);//用户使用机会
                    $debug_new_chance_num = $fans['jihui'];//用户当前剩余机会
                    $debug_user_chance_total = (int)$debug_used_chance + (int)$debug_new_chance_num;//用户机会总计
                    if ($config['yx_lt_chance_limit']<$debug_user_chance_total){
                        $remain_num=0;
                        $show_no_chance_num = 1;
                        $where = ['uid'=>$fans['uid'],'themeid'=>$themeid];
                        $data = ['jihui'=>0];
                        self::updateUserInfoByWhere($where,$data);
                    }
                }
                //自动修正 用户抽奖机会

                if ($remain_num>0){
                    $can_lt = true;
                    $tips = '您还剩'.$remain_num.'次抽奖机会';
                }else{
                    $lt_btn_txt = '继续抽奖';
                    $tips = '暂无抽奖机会';
                    if ($show_no_chance_num>0){
                        $where = ['uid'=>$fans['uid'],'themeid'=>$themeid];
                        $data = ['show_modal_num'=>$show_no_chance_num-1];
                        self::updateUserInfoByWhere($where,$data);
                    }
                }
            }else{
                $method_list = self::getLotteryMethod(0,$themeid,$config,false,true);//抽奖攻略 为了定时任务自动增加抽奖机会和插入新定时领取
                $can_lt = false;
                $tips ='请先登录';
                $lt_btn_txt = '请先登录';
                $remain_num= 0;
            }

            //判断抽奖的时间
            $now = time();
            if (!$config['is_limit_end_time']){
                //不限制取活动时间
                $config['yx_lt_begintime'] = $theme['begintime'];
                $config['yx_lt_endtime'] = $theme['endtime'];
            }
            if ($now<$config['yx_lt_begintime']){
                $can_lt = false;
                $tips ='抽奖未开始';
                $lt_btn_txt = '抽奖未开始';
            }
            if ($now>$config['yx_lt_endtime']){
                $can_lt = false;
                $tips ='抽奖活动结束';
                $lt_btn_txt = '抽奖结束';
            }

            //判断所有的商品的库存是否为0  停止抽奖
            $all_qty = self::getAllPrizeQty($themeid);
            if ($all_qty<=0){
                $can_lt = false;
                $tips ='抽奖活动结束';
                $lt_btn_txt = '抽奖结束';
            }
            //判断后台设置是否正确
//            $all_pr = (int)self::getAllPrizePr($themeid);
//            if ($all_pr!=100){
//                $can_lt = false;
//                $error_txt = '配置错误01，请检查后台【奖品列表】';
//                $lt_btn_txt = '系统配置出错';
//            }
            //判断奖品个数是否为8个
            $prize_total = count(self::getFontPrizeList($themeid));
            if ($prize_total!=8){
                $can_lt = false;
                $error_txt = '配置错误02，请检查后台【奖品列表】';
                $lt_btn_txt = '系统配置出错';
            }
            //判断员工是否参与抽奖 移动到抽奖的工作中提示
            if (!$config['yx_lt_has_worker'] && is_worker($themeid)){
                $can_lt = false;
                //员工不可参与抽奖
                $tips = '';
                $lt_btn_txt = '员工不可参与抽奖';
            }
            //判断重复性
            $is_double = $config['yx_lt_double_flag'];
            $double_num = self::getDoublePrizeCount($themeid);
            //未中奖奖项
            $free_list = self::getPrizeList($themeid,'','',1,2,0,0);
            $free_count = count($free_list);
            //必中奖
            $bizhong_list = LotteryModel::getPrizeList($themeid,'','',0,3,0,0);
            $bizhoing_count = count($bizhong_list);

            if ($is_double==0 && $double_num>0){
                $can_lt = false;
                $error_txt = '配置错误03，请检查后台【奖品列表】';
                $lt_btn_txt = '系统配置出错';
            }
            if ($is_double==1 && $double_num<=0){
                $can_lt = false;
                $error_txt = '配置错误04，请检查后台【奖品列表】';
                $lt_btn_txt = '系统配置出错';
            }
            if ($is_double==1){
                //重复性中奖配置错误判断
                if ($double_num<=0){
                    $can_lt = false;
                    $error_txt = '配置错误05，请检查后台【奖品列表】';
                    $lt_btn_txt = '系统配置出错';
                }
//                if ($free_count>=1){
//                    $can_lt = false;
//                    $error_txt = '配置错误06，请检查后台【奖品列表】';
//                    $lt_btn_txt = '系统配置出错';
//                }
            }else{
                //唯一性中奖配置错误判断
//                if ($free_count<1){
//                    $can_lt = false;
//                    $error_txt = '配置错误07，请检查后台【奖品列表】';
//                    $lt_btn_txt = '系统配置出错';
//                }
//                if ($bizhoing_count<1){
//                    $can_lt = false;
//                    $error_txt = '配置错误08，请检查后台【奖品列表】';
//                    $lt_btn_txt = '系统配置出错';
//                }
                //判断大库存奖品数必须大于抽奖机会上限
                $big_prize_count = self::getBigQtyPrizeCount($themeid);
                if ($big_prize_count<$config['yx_lt_chance_limit']){
                    $can_lt = false;
                    $error_txt = '配置错误09，请检查后台【奖品列表】';
                    $lt_btn_txt = '系统配置出错';
                }
            }
            if ($error_txt){
                if (isset($error_txt['msg'])){
                    $lt_btn_txt = $error_txt['msg'];
                }else{
                    $lt_btn_txt = $error_txt;
                }
                $can_lt = false;
            }

            $my_prize = self::getMyPrizeInfo($themeid,$config,$uid);
            $open_red_package = $config['yx_lt_open_red_package'];

            $prize_info = self::getGridList($theme['id'],$config);

            $record_list = self::getRecordList($themeid,$config,$fans['nickname'],true);//中奖记录

            $lose_lottery_info = self::getLoseLotteryInfo($themeid);//抽奖机会使用完毕的信息集合
            $rules = self::getRules($config);//活动规则
            $has_lucky_star = self::getHasLuckyStar($uid,$themeid,-2);
            $lucky_star_info = $has_lucky_star?self::getLuckyStarInfo($uid,$theme,$config):[];
            $friend_help_list = self::getFriendHelpInfo($theme['id'],$config,$uid);
            $show_tip = self::getOldOneTip($themeid,$uid,$fans,true);
            $show_my_prize = false;
            //判断唯一性兑换
            if (!$config['yx_lt_convert_only']){
                //获取用户中奖记录
                $user_flag = (int)self::getUserFlag($fans['uid'],$themeid);
                $yx_lt_chance_limit = (int)$config['yx_lt_chance_limit'];
                if ($user_flag>=$yx_lt_chance_limit){
                    $show_my_prize= true;
                }
            }
            //新版本增加
            if (!$uid){
                $can_lt = false;
                $tips ='请先登录';
                $lt_btn_txt = '请先登录';
            }
            $format_res = [
                'error_txt'=>$error_txt,
                'yx_lt_top_img'=>$config['yx_lt_top_img'],
                'top_img'=>$top_img,
                'lt_btn_txt'=>$lt_btn_txt,
                'remain_num'=>$remain_num,
                'tips'=>$tips,
                'can_lt'=>$can_lt,
                'show_no_chance_num'=>$show_no_chance_num,

                'prize_info'=>$prize_info,
                'record_list'=>$record_list,
                'method_list'=>$method_list,
                'lose_lottery_info'=>$lose_lottery_info,
                'rules'=>$rules,
                'has_lucky_star'=>$has_lucky_star,
                'lucky_star_info'=>$lucky_star_info,
                'friend_help_list'=>$friend_help_list,

                'my_prize'=>$my_prize,
                'open_red_package'=>$open_red_package,
                'show_tip'=>$show_tip,
                'show_my_prize'=>$show_my_prize,
            ];
            return $format_res;
        } catch (Exception $e) {
            var_dump($e->getMessage());die();
        }
    }
    //抽奖动作
    public static function LtRes($theme,$config,$fromuid,$uid,$workerid=0)
    {
        global $_G,$_S;
        if (empty($uid)){
            return ;
        }
        try {
            $themeid = $theme['id'];
            $fans = self::getUserInfoById($uid,$themeid);
            if (MODULE_NAME=='ew68743' || MODULE_NAME=='tp0210' || MODULE_NAME=='yx18900'){
                $i = date('i');
                $s = date('s');
                if (($i%5==0 && ($s=='00' || $s=='01' || $s=='02')) || ($i%5==4 && ($s=='58' || $s=='59'))){
                    return self::errorReturn($config,$themeid,$uid,$fans,';奖池更新中，请刷新后继续抽奖');
                }
            }
            //判断是否更新抽奖奖品组
//            self::setTimeChangePrizeGroupStatus($themeid);
            //判断抽奖的时间
            $now = time();
            if (!$config['is_limit_end_time']){
                //不限制取活动时间
                $config['yx_lt_begintime'] = $theme['begintime'];
                $config['yx_lt_endtime'] = $theme['endtime'];
            }
            if ($now<$config['yx_lt_begintime']){
                $error_txt =';抽奖未开始';
                return self::errorReturn($config,$themeid,$uid,$fans,$error_txt);
            }
            if ($now>$config['yx_lt_endtime']){
                $error_txt =';抽奖活动结束';
                return self::errorReturn($config,$themeid,$uid,$fans,$error_txt);
            }
            //判断员工是否参与抽奖
            if (!$config['yx_lt_has_worker'] && is_worker($themeid)){
                $error_txt = ';员工不可参与抽奖';//员工不可参与抽奖
                return self::errorReturn($config,$themeid,$uid,$fans,$error_txt);
            }

            $error_txt = self::checkBaseError($theme);
            $has_winning = false;
            $lose_info = [
                'title'=>"· 很遗憾 未中奖 ·",
                'content'=>'邀请好友参与活动，可获得抽奖机会',
                'icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/cry.png',
                'btn_txt'=>'知道了'
            ];
            $has_info = [];
            //判断是否存在抽奖机会
            $lottery_num = self::getUserUsedChance($config,$fans,$themeid,$uid);
            if ($lottery_num<1) {
                $format_res = [
                    'error_txt'=>'暂无抽奖机会',
                    'has_winning'=>$has_winning,
                    'lose_info'=>$lose_info,
                    'has_info'=>$has_info,
                    'remain_num'=>0,
                    'can_lt'=>false,
                    'show_tips'=>'暂无抽奖机会',
                    'lt_btn_txt'=>'暂无抽奖机会',
                    'my_convert_info'=>[],
                ];
                return $format_res;
            }

            $get_lt = [];
            $free_lt = self::getLoseLtPrize($themeid);//查询是否存在谢谢参与
            $format_prize = self::getUserCanGetPrize($themeid,$uid,$config);
            if ($format_prize['bizhiong_arr']) {
                $bigzhong_res = self::getPrizeRes($format_prize['bizhiong_arr']);
                if ($bigzhong_res['error']){
                    return self::errorReturn($config,$themeid,$uid,$fans,$bigzhong_res['error']+1000);
                }
                $get_lt = $bigzhong_res['get_lt'];
            }
            if (!$get_lt){
                if ($format_prize['default_arr']) {
                    $deffault_res = self::getPrizeRes($format_prize['default_arr']);
                    if ($deffault_res['error']){
                        return self::errorReturn($config,$themeid,$uid,$fans,$deffault_res['error']+2000);
                    }
                    $get_lt = $deffault_res['get_lt'];
                }
                if(!$get_lt){
                    //正常、必中奖项都没有满足条件
                    if (!$free_lt){//不存在谢谢参与
                        return self::errorReturn($config,$themeid,$uid,$fans,3000);
                    }else{
                        $get_lt = $free_lt;
                    }

                }
            }

            //拦截中奖奖品信息 判断库存以及中奖概率
            $prize_item = self::getPrizeItemById($get_lt['p_id'],$themeid);
            if ($prize_item['qty']==0 || $prize_item['pr']==0 || $prize_item['status']!=1){
                return self::errorReturn($config,$themeid,$uid,$fans,4000);
            }

            //中奖表插入记录
            $record_data = [
                'p_id'=>$get_lt['p_id'],
                'uid'=>$fans['uid'],
                'themeid'=>$themeid,
                'convert_code'=>GetRandConvertCode(),
                'status'=>1
            ];

            //插入中奖记录表
            if ($get_lt['type']=='red_envelope') {
                //判断是红包奖品

                //红包类型判断是否超过发放数量 超过使用未中奖
                //获得指定红包今日的发放数量
                $send_num = self::getRedPackageSendNum($themeid,$get_lt['p_id']);
                //获得指定红包今日的发放金额
                $rand_amount = self::randFloat($get_lt['red_envelopes_amount_min'],$get_lt['red_envelopes_amount_max']);

                $can_send_red_package = self::checkRedPackageLimit($send_num,$get_lt,$rand_amount,$config,$themeid,$workerid,false);
                if (!$can_send_red_package) {
                    //本次获取中奖奖项红包达到今日发放数量 替换未中奖奖项

                    if (!$free_lt){//不存在谢谢参与
                        return self::errorReturn($config,$themeid,$uid,$fans,3000);
                    }else{
                        $get_lt = $free_lt;
                    }
                } else {
                    $record_data['from_type']='red_envelope';
                    $res = self::insertLtFlag($record_data);
                    $f_id = $insertid;
                    //插入抽奖红包记录表
                    $red_pachage_data = [
                        'uid'=>$uid,
                        'amount'=>$rand_amount,
                        'f_id'=>$f_id,
                        'p_id'=>$get_lt['p_id'],
                        'status'=>1,
                        'themeid'=>$themeid
                    ];
                    $get_lt['title'] = '红包'.$rand_amount.'元';
                    $get_lt['red_envelopes_amount_max'] = $rand_amount;
                    self::insertRpFlag($red_pachage_data);
                    //用户日志收集
                    $log_msg = $get_lt['title'];
                    Userdata::addLog($themeid, $fans['uid'], 19, $log_msg);

                    //更新用户红包金额
                    $old_rp_amount = $fans['new_rp_amount'];
                    $new_rp_amount = bcadd($old_rp_amount,$rand_amount,2);
                    $res = self::updateFansInfo($fans['uid'],$themeid,['new_rp_amount'=>$new_rp_amount]);
                    //判断是否是自动发放
                    if ($_S['autored']==1){
                        self::Withdraw($themeid,$config,$uid,$fromuid);
                    }
                }
            } else {
                $record_data['from_type']='default';
                self::insertLtFlag($record_data);
            }



            //更新奖项库存量   需测试
            $update_lt_item_sql = "update ".tablename(yx_lt_prize)." set qty=qty-1,out_qty=out_qty + 1 where p_id='".$get_lt['p_id']."' and themeid='$themeid'";
//            $lt_item = db_update(yx_lt_prize,['qty'=>-1,'out_qty'=>+1],['p_id'=>$get_lt['p_id']]);
            $lt_item = db_find($update_lt_item_sql);

            //用户表 剩余抽检次数减 抽奖机会表加
            $chance_num = $fans['jihui'];
            $new_chance_num = $chance_num-1;
            $update_fans_jihui_sql = " update ".tablename(t_fans)." set jihui=jihui-1 where uid='".$fans['uid']."' and themeid='".$themeid."'";
//            $res = self::updateFansInfo($fans['uid'],$themeid,['jihui'=>$new_chance_num]);
            $res = db_find($update_fans_jihui_sql);

            //插入使用抽奖机会的记录
            $insert_data = [
                'uid'=>$fans['uid'],
                'type'=>'system',
                'chance'=>-1,
                'date'=>date("Y-m-d",time()),
                'themeid'=>$themeid,
                'from_uid'=>$uid
            ];
            //抽奖机会表
            $result = self::insertChance($insert_data);

            //获取当前奖项在前端展示数组中的第几位
            $checked_key = 0;
            $list = self::getFontPrizeList($themeid);
            foreach ($list as $index=>$item) {
                if ($item['p_id']==$get_lt['p_id']) {
                    $checked_key=$index;
                    break;
                }
            }
            if ($get_lt['default_type']!=2) {
                $has_info = [
                    'title'=>'· 恭喜中奖了 ·',
                    'img'=>$get_lt['small_img'],
                    'name'=>'',
                    'name2'=>$get_lt['title'],
                    'type'=>$get_lt['type'],
                    'amount'=>$get_lt['red_envelopes_amount_max'],
                    'tips'=>$get_lt['desc_content'],
                    'p_id'=>$get_lt['p_id'],
                    'checked_key'=>$checked_key
                ];
                $log_msg = $get_lt['title'];
                $has_winning = true;
            }else{
                $lose_info['checked_key']=$checked_key;
                $log_msg = '未中奖';
            }
            Userdata::addLog($themeid, $fans['uid'], 19, $log_msg);
            $fans['jihui'] = $fans['jihui']-1;
            $remain_num = self::getUserUsedChance($config,$fans,$themeid,$uid);
            if ($remain_num>0){
                $can_lt = true;
                $lt_btn_txt = '继续抽奖';
                $tips = '还剩'.$remain_num.'次';
            }else{
                $can_lt = false;
                $lt_btn_txt = '获取更多机会';
            }
            $format_res = [
                'error_txt'=>$error_txt,
                'has_winning'=>$has_winning,
                'lose_info'=>$lose_info,
                'has_info'=>$has_info,
                'remain_num'=>$remain_num,
                'can_lt'=>$can_lt,
                'tips'=>$tips,
                'lt_btn_txt'=>$lt_btn_txt,
            ];
            return $format_res;

        } catch (Exception $e) {

        }
    }


    //获取抽奖机会的提醒
    public static function errorReturn($config,$themeid,$uid,$fans,$error=''){
        $lt_btn_txt = '开始抽奖';
        $remain_num = 0;
        $tips = '';
        $can_lt = false;
        $remain_num = self::getUserUsedChance($config,$fans,$themeid,$uid);
        if ($remain_num>0){
            $can_lt = true;
        }else{
            $lt_btn_txt = '获取更多机会';
        }
        $tips = '还剩'.$remain_num.'次';
        $format_res = [
            'error_txt'=>'抽奖失败，请重试'.$error.'！',
            'has_winning'=>false,
            'lose_info'=>[],
            'has_info'=>[],
            'remain_num'=>$remain_num,
            'can_lt'=>$can_lt,
            'tips'=>$tips,
            'lt_btn_txt'=>$lt_btn_txt,
        ];
        return $format_res;
    }

    //获取抽奖机会的提醒
    public static function getOldOneTip($themeid,$uid,$fans,$update_flag = false)
    {
        if (empty($uid)){
            return ;
        }
        $res = [];
        $msg = '';
        if ($fans['jihui']>0){
            $sql = " select * from ".tablename(yx_lt_chance)." where themeid=$themeid and uid=$uid and chance>0 and is_tip=0 order by c_id";
            $res = db_find($sql);
        }
        if ($res){
            $add_chance = $res['chance'];
            $temp_arr = [
                'system_add'=>'恭喜您获得'.$add_chance.'次抽奖机会',
                'lucky_star'=>'进入链接获得'.$add_chance.'次抽奖机会',
                'self_order'=>'自己下单获得'.$add_chance.'次抽奖机会',
                'share_moments'=>'转发朋友圈获得'.$add_chance.'次抽奖机会',
                'friend_order'=>'好友报名获得'.$add_chance.'次抽奖机会',
                'friend_view'=>'好友到访获得'.$add_chance.'次抽奖机会',
                'timeset'=>'定时领取获得'.$add_chance.'次抽奖机会',
            ];
            if ($res['type']!='lucky_star'){
                $msg = $temp_arr[$res['type']];
            }
            $update_data = ['is_tip'=>1];
            if ($update_flag){
                $after_res = db_update(yx_lt_chance,$update_data,['c_id'=>$res['c_id'],'themeid'=>$themeid]);
            }
//
        }
        return $msg;
    }

    public static function randFloat($min,$max,$num=2)
    {
        if ($min==$max){
            return  $max;
        }
        return floatval(mt_rand(round($min*100),round($max*100))/100);
    }

    //我的奖品
    public static function UserPrize($theme,$config,$uid)
    {
        try {
            $themeid = $theme['id'];
            $error_txt = self::checkBaseError($theme);
            $my_prize = self::getMyPrizeInfo($themeid,$config,$uid);
            $open_red_package = $config['yx_lt_open_red_package'];
            $format_res = [
                'error_txt'=>$error_txt,
                'open_red_package'=>$open_red_package,
                'red_package_info'=>$my_prize['red_package_info'],
                'prize_info'=>$my_prize['prize_info'],
                'btm_txt'=>$my_prize['btm_txt']
            ];
            return $format_res;
        }catch (Exception $e){

        }
    }

    public static function createAppUrl($do, $query = array()){
        global $_G, $_P;
        if ($do=='dopay'){
            $url = '';
        }else{
            $str ='?';

            if (!empty($_P['isqr'])){
                $query['isqr']=1;
            }
            foreach ($query as $key => $value) {
                if ($key <> 'themeid' && $key <> 'fromuid' &&  $key <> 'a'){
                    $str .= "&" . $key ."=" . $value;
                }
            }

            $str = str_replace("?&", "?", $str);
            //rewrite ^/(.*)/(.*)/(.*)/(.*)/(.*).aspx?(.*)$ /app/index.php?c=entry&m=$1&i=$2&themeid=$3&fromuid=$4&do=$5&$6 break;
            //rewrite ^/(.*)/(.*)/(.*)/(.*)/(.*).aspx?(.*)$ /app/index.php?$6&c=entry&m=$1&i=$2&themeid=$3&fromuid=$4&do=$5 break;

            if (empty($query['themeid'])){
                $query['themeid']=0;
            }
            if (empty($query['fromuid'])){
                $query['fromuid']=intval($_G['member']['uid']);
            }
            $url = MODULE_NAME . "/" . $_G['mpid'] . "/" . $query['themeid'] ."/" . $query['fromuid'] . "/" . $do .".aspx" . $str;
            if (!empty($query['themeid'])) {
                $item = Theme::getById($query['themeid']);
                if(!empty($item['softkey'])) {
                    $url = $url . "&soft=" . $item['softkey'];
                }
            }
        }
        return $url;
    }


    //兑换奖品
    public static function ConvertPrize($theme,$config,$uid,$f_id,$system,$fromtype='mobile')
    {
        global $_G, $_P;
        if (empty($uid)){
            return ;
        }
        try {
            $themeid = $theme['id'];
            $fans = self::getUserInfoById($uid,$themeid);
            $error_txt = '';
            $lt_flag_item = self::getLtFlagItem($themeid,$uid,$f_id);
            $back_img = $config['yx_lt_convert_back_img'];
            $lt_prize_item = self::getLtFlagAndPrizeInfo($themeid,$f_id);
            if ($lt_prize_item['status']!=1 && $lt_prize_item['status']!=3) {
                $lt_prize_item = [];
            }
            if ($lt_prize_item && $lt_prize_item['status']==1) {
                $where = [
                    'f_id'=>$f_id
                ];
                $data = ['status'=>3];
                self::editLtFlagItem($where,$data);
            }else{
                $error_txt = '记录不存在或已兑换';
            }
            $prize_img = $lt_prize_item['small_img'];
            $title ='中奖啦，恭喜您抽中';
            $convert_card = $lt_prize_item['convert_code'];
            $method = $theme['jubf'];
            $tel = $theme['mobile'];
            $mobile = $config['district'].$config['addresstxt'];
            $btn_txt = $config['yx_lt_convert_btn'];
            $btm_tips = $config['yx_lt_convert_btm_tips'];
            $btm_tips2 = '';
            if (!$config['yx_lt_convert_only']){
                $btm_tips2 = '每个相同的奖品只能兑换一次';
            }

            if ($fromtype=='mobile'){
                $sharedata = [
                    'themeid'=>$themeid,
                    'code'=>$convert_card,
                    'op'=>'display'
                ];
                if ($system['gongzhong'] =='1'){
                    $domaintxt = $system['domainhead1'];
                }else{
                    $domaintxt = DOMAIN0;
                }
                $inputurl = $_G['url_scheme'].$domaintxt."/".createMobileUrl('X_ltVerif',$sharedata);
                $inputurl = QRURLNEW. urlencode($inputurl);
            }else{
                $scene = MODULE_NAME . "-" . $theme['id'] . "-".$uid."-" . $theme['softkey']."-".$f_id;
                $inputurl = Poster::CreateScene($system, $scene, $config, 'Worker/pages/w_verify/w_verify');
            }

            $format_res = [
                'error_txt'=>$error_txt,
                'back_img'=>$back_img,
                'prize_img'=>$prize_img,
                'prize_name'=>'【 '.$lt_prize_item['name'].' 】'.'- '.$lt_prize_item['title'],
                'title'=>$title,
                'convert_card'=>$inputurl,
                'method'=>$method,
                'tel'=>"电话：".$tel,
                'mobile'=>"地址：".$mobile,
                'btn_txt'=>$btn_txt,
                'btm_tips'=>$btm_tips,
                'btm_tips2'=>$btm_tips2,
            ];
            return $format_res;
        } catch (Exception $e) {
            var_dump($e->getMessage());die();
        }
    }

    //获取随机虚拟中奖记录
    public static function dummyConvert($config,$theme,$system,$fromtype)
    {
        global $_G, $_P;
        $themeid = $theme['id'];

        if (strstr($config['softtag0'],"婚纱")!==false ){
            $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+1045;
        }else{
            $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+2545;
        }
        if ($config['touxiang']==0) {
            $xunisql = "SELECT nickname AS username,avatar FROM " . tablename(t_2019fans) .
                " WHERE id >". $kaishishu ." and avatar!=''   ";
        } else {
            $xunisql = "SELECT username,avatar FROM " . tablename(t_2019fans) .
                " WHERE id >". $kaishishu ." and avatar!=''  ";
        }
        $res = db_select($xunisql);
        $rand_key = rand(0,count($res)-1);
        $fans_info = $res[$rand_key];

        $prize_list = self::getShowRatiioItems($themeid);
        $rand_prize_key = rand(0,count($prize_list)-1);
        $lt_prize_item = $prize_list[$rand_prize_key];
        $back_img = $config['yx_lt_convert_back_img'];

        $prize_img = $lt_prize_item['small_img'];
        $title ='中奖啦，恭喜您抽中';
        $method = $theme['jubf'];
        $tel = $theme['mobile'];
        $mobile = $config['district'].$config['addresstxt'];
        $btn_txt = $config['yx_lt_convert_btn'];
        $btm_tips = $config['yx_lt_convert_btm_tips'];
        $btm_tips2 = '';
        if (!$config['yx_lt_convert_only']){
            $btm_tips2 = '每个相同的奖品只能兑换一次';
        }
        if ($fromtype=='mobile'){
            if ($system['gongzhong'] =='1'){
                $domaintxt = $system['domainhead1'];
            }else{
                $domaintxt = DOMAIN0;
            }
            $inputurl = $_G['url_scheme'].$domaintxt."/".createMobileUrl('index',[]);
            $inputurl = QRURLNEW. urlencode($inputurl);
        }else{
            $scene = MODULE_NAME . "-" . $theme['id'] . "-0-" . $theme['softkey']."-0";
            $inputurl = Poster::CreateScene($system, $scene, $config, 'pages/index/index');
        }

        $format_res = [
            'error_txt'=>'',
            'bg_img'=>$config['yx_lt_top_img'],
            'back_img'=>$back_img,
            'prize_img'=>$prize_img,
            'prize_name'=>'【 '.$lt_prize_item['name'].' 】'.'- '.$lt_prize_item['title'],
            'title'=>$title,
            'convert_card'=>$inputurl,
            'method'=>$method,
            'tel'=>"电话：".$tel,
            'mobile'=>"地址：".$mobile,
            'btn_txt'=>$btn_txt,
            'btm_tips'=>$btm_tips,
            'btm_tips2'=>$btm_tips2,
            'username'=>$fans_info['username'],
            'avatar'=>$fans_info['avatar']
        ];
        return $format_res;
    }
    //红包提现
    public static function Withdraw($themeid,$config,$uid,$fromuid)
    {
        if (empty($uid)){
            return ;
        }
        $fans = self::getUserInfoById($uid,$themeid);
        $ordersn = getMillisecond();
        $red_package_amount = $fans['new_rp_amount'];
        $red_package_min_amount = $config['red_package_min_amount'];
        if ($red_package_amount>$red_package_min_amount){
            //发放红包的时候更新  红包发放表的id到抽奖的红包记录表中
            $comm_id = self::UserWithdraw($red_package_amount,$themeid,$fans,$ordersn,$fromuid);
            if ($comm_id){
                //用户日志收集
                Userdata::addLog($themeid, $fans['uid'], 14, '抽奖红包提现');
                self::updateRpFlag(['uid'=>$uid,'themeid'=>$themeid],['status'=>3,'tc_id'=>$comm_id]);
                //用户红包金额提现后置空
                $res = self::updateFansInfo($fans['uid'],$themeid,['new_rp_amount'=>0]);
                return true;
            }
        }
        return false;
    }

    /**
     * Desc:增加抽奖机会接口
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/28 9:45 下午
     * @param $type
     * @param $fans
     * @param $themeid
     * @param $fromuid
     */
    public static function apiAddChance($type,$fans,$themeid,$fromuid,$config,$t_id=0)
    {
        global $_S;
        $can_enter = false;
        if ($config['yx_lt_has_worker'] || (!$config['yx_lt_has_worker'] && !is_worker($themeid))){
            $can_enter = true;
        }
        //判断员工是否参与抽奖
        if ($can_enter){
            //本次增加机会
            $add_chance_num = self::getChanceNumsByType($type,$themeid,$fans,$config);
            if ($add_chance_num>0){
                //使用机会
                $used_chance = self::getUserRecordsByType($fans['uid'],'used',$themeid,false);
                //剩余机会
                $new_chance_num = $fans['jihui'];
                $total_chance = (int)$used_chance+(int)$new_chance_num+$add_chance_num;
                if ($total_chance<=$config['yx_lt_chance_limit']){
                    //判断是好友下单的类型
//                    $themyrecord = Record::getLastGroupByUid($fans['uid'],$themeid);
                    $themyrecord = db_get(t_record,['uid'=>$fans['uid'],'themeid'=>$themeid,'status >'=>0]);
                    if ($type=='friend_order' && $config['yx_lt_main_order'] && !$themyrecord){
                        return '';
                    }
                    $insert_data = [
                        'uid'=>$fans['uid'],
                        'type'=>$type,
                        'date'=>date("Y-m-d",time()),
                        'chance'=>$add_chance_num,
                        'themeid'=>$themeid,
                        'from_uid'=>$fromuid,
                        't_id'=>$t_id
                    ];

                    if (is_int($add_chance_num)){
                        if ($type!='friend_view' && $type!='friend_help'){
                            $chance_num = $fans['jihui'];
                            $new_chance_num = $chance_num+$add_chance_num;
                            $res = self::insertChance($insert_data);
                        }else if ($type=='friend_view'){
                            $limit_chance_num = $config['yx_lt_friend_view_limit'];
                            $set_lotteryview = $config['yx_lt_friend_view'];
                            $flag_num = self::getUserRecordsByType($fans['uid'],'friend_view',$themeid);
                            $new_flag_num = $flag_num+1;
                            $old_limit_chance = $new_flag_num/$set_lotteryview;
                            if ($old_limit_chance>$limit_chance_num){
                                $insert_data['chance'] = 0;
                            }
                            $chance_num = $fans['jihui'];
                            $new_chance_num = $chance_num+$add_chance_num;
                            //判断当前剩余机会以及已使用机会是否大于抽奖机会上限
                            if ($config['yx_lt_chance_limit']>=$total_chance){
                                $insert_data['chance'] = 0;
                                $log_msg = self::getTypeStr($type).'；达到抽奖机会上限，不增加机会';
                                Userdata::addLog($themeid, $fans['uid'], 18, $log_msg,$fans['workerid'],$fromuid);
                            }
                            $res = self::insertChance($insert_data);
                        }else{
                            //好友助力
                            $limit_chance_num = $config['yx_lt_friend_help_limit'];
                            $set_lotteryview = $config['yx_lt_friend_help'];
                            $flag_num = self::getUserRecordsByType($fans['uid'],'friend_help',$themeid);
                            $new_flag_num = $flag_num+1;
                            $old_limit_chance = $new_flag_num/$set_lotteryview;
                            if ($old_limit_chance>$limit_chance_num){
                                $insert_data['chance'] = 0;
                            }
                            $chance_num = $fans['jihui'];
                            $new_chance_num = $chance_num+$add_chance_num;
                            //判断当前剩余机会以及已使用机会是否大于抽奖机会上限
                            if ($config['yx_lt_chance_limit']>=$total_chance){
                                $insert_data['chance'] = 0;
                                $log_msg = self::getTypeStr($type).'；达到抽奖机会上限，不增加机会';
                                Userdata::addLog($themeid, $fans['uid'], 18, $log_msg,$fans['workerid'],$fromuid);
                            }
                            $res = self::insertChance($insert_data);
                        }

                    }else{
                        if ($type=='friend_view'){
                            $set_lotteryview = $config['yx_lt_friend_view'];
//                            $flag_num = self::getUserRecordsByType($fans['uid'],'friend_view',$themeid);
                            $flag_num = self::getUserRecordsByTypeGroupByFromUid($fans['uid'],'friend_view',$themeid,false,true);
                            $has_friend_flag = self::getFriendViewChanceFlag($themeid,$fans['uid'],$fromuid);

                            if ($has_friend_flag<1) {
                                $new_flag_num = $flag_num+1;
                                if (is_int($new_flag_num/$set_lotteryview)){
                                    //判断好友增加的次数是否达到上限
                                    $limit_chance_num = $config['yx_lt_friend_view_limit'];
                                    $old_limit_chance = $new_flag_num/$set_lotteryview;
                                    if ($old_limit_chance<=$limit_chance_num){
                                        $chance_num = $fans['jihui'];
                                        $new_chance_num = $chance_num+1;
                                        $insert_data['chance'] = 1;
                                    }else{
                                        $insert_data['chance'] = 0;
                                    }
                                }else{
                                    $insert_data['chance'] = 0;
                                }
                                $res = self::insertChance($insert_data);
                            }
                        }else{
                            //好友助力
                            $set_lotteryview = $config['yx_lt_friend_help'];
                            $flag_num = self::getUserRecordsByType($fans['uid'],'friend_help',$themeid);
                            $has_friend_flag = self::getFriendViewChanceFlag($themeid,$fans['uid'],$fromuid,'friend_help');
                            if ($has_friend_flag<1) {
                                $new_flag_num = $flag_num+1;
                                if (is_int($new_flag_num/$set_lotteryview)){
                                    //判断好友增加的次数是否达到上限
//                                    $limit_chance_num = $config['yx_lt_friend_view_limit'];
                                    $limit_chance_num = $config['yx_lt_friend_help_limit'];
                                    $old_limit_chance = $new_flag_num/$set_lotteryview;

                                    if ($old_limit_chance<=$limit_chance_num){
                                        $chance_num = $fans['jihui'];
                                        $new_chance_num = $chance_num+1;
                                    }else{
                                        $insert_data['chance'] = 0;
                                    }
                                }else{
                                    $insert_data['chance'] = 0;
                                }
                                $res = self::insertChance($insert_data);
                            }
                        }

                    }

                    if ($type=='friend_view' || $type=='friend_help'){
                        $flag_num = self::getUserRecordsByTypeGroupByFromUid($fans['uid'],$type,$themeid,false,true);
                        if ($type=='friend_view'){
                            $set_lotteryview = $config['yx_lt_friend_view'];
                            $set_lottery_type_limit = $config['yx_lt_friend_view_limit'];
                        }else{
                            $set_lotteryview = $config['yx_lt_friend_help'];
                            $set_lottery_type_limit = $config['yx_lt_friend_help_limit'];
                        }
                        if ($set_lottery_type_limit<($flag_num/$set_lotteryview)){
                            $log_msg = self::getTypeStr($type).'达到上限，不增加机会';
                            Userdata::addLog($themeid, $fans['uid'], 18, $log_msg,$fans['workerid'],$fromuid);
                        }
                    }

                    if (($config['yx_lt_chance_limit']>=$new_chance_num) && $new_chance_num>0){
                        //判断当期类型是否达到最大值
                        $log_msg = self::getTypeStr($type).'，增加'.$add_chance_num.'次机会,当前机会'.$new_chance_num;
                        //用户日志收集
                        Userdata::addLog($themeid, $fans['uid'], 18, $log_msg,$fans['workerid'],$fromuid);
                        $chance_info = array(
                            'desc' => self::getTypeStr($type),
                            'num' => $add_chance_num,
                        );
                        Sms::CheckAndSendSms('lottery_new',$_S,$config,$themeid, $insert_data,$chance_info);
                        $result = self::updateFansInfo($fans['uid'],$themeid,['jihui'=>$new_chance_num]);
                    }
                    return '';
                }else{
                    $log_msg = self::getTypeStr($type).'；达到抽奖机会上限，不增加机会';
                    //用户日志收集
                    Userdata::addLog($themeid, $fans['uid'], 18, $log_msg,$fans['workerid'],$fromuid);
                    $insert_data = [
                        'uid'=>$fans['uid'],
                        'type'=>$type,
                        'date'=>date("Y-m-d",time()),
                        'chance'=>0,
                        'themeid'=>$themeid,
                        'from_uid'=>$fromuid,
                        't_id'=>$t_id
                    ];
                    $res = self::insertChance($insert_data);
                    return $res;
                }
            }else{
                if ($type=='share_moments'){
                    $is_special_share_moments = false;
                    if ((int)$config['yx_lt_first_share_moment']==0 && ((int)$config['yx_lt_second_share_moment']>0 || (int)$config['yx_lt_third_share_moment']>0)){
                        $is_special_share_moments = true;
                    }
                    if ((int)$config['yx_lt_first_share_moment']==0 && (int)$config['yx_lt_second_share_moment']==0 && (int)$config['yx_lt_third_share_moment']>0){
                        $is_special_share_moments = true;
                    }
                    $today_flag = self::getUserRecordsByType($fans['uid'],'share_moments',$themeid,true);//朋友圈
                    //判断今日是否存在
                    if ($today_flag<1){
                        if ($is_special_share_moments){
                            $insert_data = [
                                'uid'=>$fans['uid'],
                                'type'=>$type,
                                'date'=>date("Y-m-d",time()),
                                'chance'=>0,
                                'themeid'=>$themeid,
                                'from_uid'=>$fromuid,
                                't_id'=>$t_id
                            ];
                            $res = self::insertChance($insert_data);
                            return $res;
                        }
                    }else{
                        return false;
                        //下面逻辑处理有漏洞暂时注释
                        //处理后增加转发增加机会 原始记录占用问题
                        $moments = self::getUserRecordsByType($fans['uid'],'share_moments',$themeid);
                        //判断今日是否存在分享朋友圈记录
                        $today_share_moment_chance_flag = self::getShareMomentChance($fans['uid'],$themeid,true);
                        if ($moments==1){
                            $one_day = (int)$config['yx_lt_first_share_moment'];//第一天
                            if ($today_share_moment_chance_flag && $today_share_moment_chance_flag['chance']==0 && $one_day>0){
                                $add_chance_num = $one_day;
                            }
                        }elseif ($moments==2){
                            $two_day = (int)$config['yx_lt_second_share_moment'];//第二天
                            if ($today_share_moment_chance_flag && $today_share_moment_chance_flag['chance']==0 && $two_day>0){
                                $add_chance_num = $two_day;
                            }
                        }elseif ($moments==3){
                            $third_day = (int)$config['yx_lt_third_share_moment'];//第三天
                            if ($today_share_moment_chance_flag && $today_share_moment_chance_flag['chance']==0 && $third_day>0){
                                $add_chance_num = $third_day;
                            }
                        }
                        if ($add_chance_num>0){
                            //判断今日分享朋友圈记录是否增加机会
                            //获取当前用户机会数
                            $used_chance = self::getUserRecordsByType($fans['uid'],'used',$themeid,false);
                            //剩余机会
                            $new_chance_num = $fans['jihui'];
                            $total_chance = (int)$used_chance+(int)$new_chance_num+$add_chance_num;
                            if ($total_chance<=$config['yx_lt_chance_limit']){
                                //修改今日占位为增加抽奖机会记录 给当前用户机会补发
                                $res = db_update(yx_lt_chance,['chance'=>$add_chance_num],['c_id'=>$today_share_moment_chance_flag['c_id']]);
                                $chance_num = $fans['jihui'];
                                $new_chance_num = $chance_num+$add_chance_num;
                                $result = self::updateFansInfo($fans['uid'],$themeid,['jihui'=>$new_chance_num]);
                                $log_msg = self::getTypeStr($type).'，增加'.$add_chance_num.'次机会,当前机会'.$new_chance_num;
                                //用户日志收集
                                Userdata::addLog($themeid, $fans['uid'], 18, $log_msg,$fans['workerid'],$fromuid);
                            }else{
                                $log_msg = self::getTypeStr($type).'；达到抽奖机会上限，不增加机会';
                                //用户日志收集
                                Userdata::addLog($themeid, $fans['uid'], 18, $log_msg,$fans['workerid'],$fromuid);
                            }
                        }

                    }
                }
            }
        }

    }

    /**
     * Desc:获取类型的中文
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/25 22:21
     * @param $type
     * @return string
     */
    public static function getTypeStr($type)
    {
        $str = '';
        switch ($type){
            case 'no_sign_up':
                $str='幸运星';
                break;
            case 'self_order':
                $str = '用户报名';
                break;
            case 'share_moments':
                $str = '转发朋友圈';
                break;
            case 'friend_order':
                $str = '好友报名';
                break;
            case 'friend_view':
                $str = '好友到访';
                break;
            case 'timeset':
                $str = '定时领取';
                break;
            default:
                break;
        }
        return $str;
    }

    /**
     * Desc:获取对应类型的增加的增加的机会次数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/28 8:46 下午
     * @param $type --1 未报名 2 自己报名 3转发朋友圈 4好友报名 5好友到访 6定时领取
     * @param $themeid
     * @param $fans
     * @param $config
     * @return int|string
     */
    public static function getChanceNumsByType($type,$themeid,$fans,$config)
    {
        $add_chance_num = 0;
        $chance_limit = (int)$config['yx_lt_chance_limit'];//抽奖次数上限
        $default_chance = (int)$config['yx_lt_no_sign_up'];//未报名
        $register_chance = (int)$config['yx_lt_self_order'];//自己下单
        $invite_order_chance = (int)$config['yx_lt_friend_order'];//好友下单
        $fanpaipengyouquan = (int)$config['yx_lt_share_moment_user_type'];//0未报名+已报名 1已报名
        $config['yx_lt_friend_view'] = (int)$config['yx_lt_friend_view'];
        if ($config['yx_lt_friend_view']>0){
            $lotteryview_chance = number_format(1/$config['yx_lt_friend_view'],2);
        }else{
            $lotteryview_chance = 0;
        }
//        好友助力
        $config['yx_lt_friend_help'] = (int)$config['yx_lt_friend_help'];
        if ($config['yx_lt_friend_help']>0){
            $lotteryhelp_chance = number_format(1/$config['yx_lt_friend_help'],2);
        }else{
            $lotteryhelp_chance = 0;
        }
        
        $one_day = (int)$config['yx_lt_first_share_moment'];//第一天
        $two_day = (int)$config['yx_lt_second_share_moment'];//第二天
        $third_day = (int)$config['yx_lt_third_share_moment'];//第三天
        $yx_lt_timeset = 1;//定时奖励次数
        switch ($type){
            case 'no_sign_up':
                //未报名
                $add_chance_num = $default_chance;
                break;
            case 'self_order':
                //自己报名
                $add_chance_num = $register_chance;
                break;
            case 'share_moments':
                //转发朋友圈
                $today_flag = self::getUserRecordsByType($fans['uid'],'share_moments',$themeid,true);//朋友圈
                $moments = self::getUserRecordsByType($fans['uid'],'share_moments',$themeid);
                if ($moments==0){
                    $add_chance_num = $one_day;
                }
                if ($moments==1){
                    $add_chance_num = $two_day;
                }
                if ($moments==2){
                    $add_chance_num = $third_day;
                }
                if (($today_flag>0 && $add_chance_num>0) || ($fanpaipengyouquan==1 && (empty($fans['username']) || empty($fans['mobile'])))){
                    $add_chance_num = 0;
                }
                break;
            case 'friend_order':
                //好友报名
                $add_chance_num = $invite_order_chance;
                break;
            case 'friend_view':
                //好友到访
                $add_chance_num = floatval($lotteryview_chance);
                break;
            case 'friend_help':
                //好友助力
                $add_chance_num = floatval($lotteryhelp_chance);
                break;
            case 'timeset':
                //定时领取
                $add_chance_num = $yx_lt_timeset;
                break;
            default:
                break;
        }
        yxlog('uid:'.$fans['uid'].'通过'.$type.'增加'.$add_chance_num.'次机会','增加抽奖机会');
        return $add_chance_num;
    }
    //更新活动粉丝表信息
    public static function updateFansInfo($uid,$themeid,$update_data)
    {
        $res = db_update(t_fans,$update_data,['uid'=>$uid,'themeid'=>$themeid]);
        if (!$res) {
            return false;
        } else {
            return true;
        }
    }
    //基础信息初始化
    public static function initInfo($themeid,$config,$uid,$from_uid)
    {
        global $_S;
        if (empty($uid)){
            return ;
        }
        if ($uid && $themeid && $config){
            $can_enter = false;
            $fans = self::getUserInfoById($uid,$themeid);
            if ($config['yx_lt_has_worker'] || (!$config['yx_lt_has_worker'] && !is_worker($themeid))){
                $can_enter = true;
            }

            //判断员工是否参与抽奖
            if ($fans && $can_enter){
                $remain_num = $fans['jihui'];
                //判断用户是否存在抽奖机会记录
                $user_chance_flag_num = self::getUserChanceByUidAndThemeId($uid,$themeid);
                if ($user_chance_flag_num<1){
                    $show_modal_num = $config['yx_lt_show_no_chance_num'];
                    self::updateFansInfo($fans['uid'],$themeid,['show_modal_num'=>$show_modal_num]);
                }
                $no_sign_up_num = min($config['yx_lt_no_sign_up'],$config['yx_lt_chance_limit']);
                //幸运星
                //不存在抽奖机会记录  系统存在未报名可抽 插入抽奖机会 更新用户剩余抽奖机会
                if ($config['yx_lt_no_sign_up'] && $remain_num <1 && $user_chance_flag_num<1 && $no_sign_up_num>=1){
                    $insert_data = [
                        'uid'=>$fans['uid'],
                        'type'=>'lucky_star',
                        'date'=>date("Y-m-d",time()),
                        'chance'=>$no_sign_up_num,
                        'themeid'=>$themeid,
                        'from_uid'=>$from_uid,
                        't_id'=>-2,
                    ];
                    $res = self::insertChance($insert_data);
                    $new_lt_counter = $remnant_num = $fans['jihui']+$no_sign_up_num;
                    //用户日志收集
                    $log_msg = '获得幸运星，增加'.$no_sign_up_num.'次机会,当前机会'.$new_lt_counter;
                    Userdata::addLog($themeid, $fans['uid'], 18, $log_msg);
                    $chance_info = array(
                        'desc' => '获得幸运星',
                        'num' => $no_sign_up_num,
                    );
                    Sms::CheckAndSendSms('lottery_new',$_S,$config,$themeid, $insert_data,$chance_info);
                    $result = self::updateFansInfo($fans['uid'],$themeid,['jihui'=>$new_lt_counter]);
                }

//                $lucky_star_num = self::getLuckyStarCount($uid,$themeid);
//                if ($config['yx_lt_lucky_star'] && $remain_num<1) {
//                    if (!$lucky_star_num) {
//                        self::insertLuckyItem($uid,$themeid);
//                        //增加一次抽奖机会
//                        $fans = self::getUserInfoById($uid,$themeid);
//                        $new_lt_counter = $fans['jihui']+$config['yx_lt_no_sign_up'];
//                        $result = self::updateFansInfo($fans['uid'],['jihui'=>$new_lt_counter,'themeid'=>$themeid]);
//                    }
//                }

                $theme = Theme::getThemeById($themeid);
                if (!$config['is_limit_end_time']){
                    //不限制取活动时间
                    $config['yx_lt_begintime'] = $theme['begintime'];
                    $config['yx_lt_endtime'] = $theme['endtime'];
                }
                //好友到访 给上一级增加抽奖机会
                if (Common::getLotteryLimitTime($_S,$config,$theme) && $config['yx_lt_friend_view']>0){
                    if ($fans['uid']==$from_uid || empty($from_uid)){
                        $from_uid =  Fans::get_now_formuid($themeid)['fromuid'];
                    }
                    yxlog(['uid'=>$uid,'fromuid'=>$from_uid],'进入抽奖判断新粉丝');
                    if ($fans['uid']!=$from_uid && $from_uid ){
                        $from_fans = LotteryModel::getUserInfoById($from_uid,$themeid);
                        $is_new_fans = self::checkNewUser($fans,$config);
                        if (!$is_new_fans){
                            Userdata::addLog($themeid, $from_uid, 17, '好友不是新粉丝，不增加机会',$fans['workerid'],$uid);
                        }
                        //判断是否是新用户
                        if ($from_fans && $is_new_fans){
                            //判断是否给上级增过机会记录
                            $has_friend_flag = self::getFriendViewChanceFlag($themeid,$from_fans['uid'],$fans['uid']);
                            if (!$has_friend_flag){
                                $is_can_add_firend_view_chance = true;
                                if ($config['yx_lt_view_user_type']) {
                                    //判断上级是否存在支付订单
                                    $themyrecord = db_get(t_record,['uid'=>$from_uid,'themeid'=>$themeid,'status >'=>0]);
//                                    $themyrecord = Record::getLastGroupByUid($from_uid, $themeid);
                                    if (!$themyrecord) {
                                        $is_can_add_firend_view_chance = false;
                                        Userdata::addLog($themeid, $from_uid, 17, '用户未支付，好友助力失败，不增加机会',$fans['workerid'],$uid);
                                    }
                                }
                                if ($is_can_add_firend_view_chance) {
                                    Userdata::addLog($themeid, $from_uid, 17, '好友助力成功',$fans['workerid'],$fans['uid']);
                                    self::apiAddChance('friend_view', $from_fans, $themeid, $fans['uid'], $config);
                                }
                            }else{
                                Userdata::addLog($themeid, $from_uid, 17, '好友已助力，不增加机会',$fans['workerid'],$uid);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Desc:判断是否是新用户
     * User: cbw
     * Time: 2021/1/9 2:55 下午
     * @param $fans
     * @return bool
     */
    public static function checkNewUser($fans,$config)
    {
        $is_new_user = false;
        //不限制
        if (!$config['yx_lt_new_fan_terms']){
            $is_new_user = true;
        }
        //手机号
        if ($config['yx_lt_new_fan_terms']==1 && !$fans['mobile']){
            $is_new_user = true;
        }
        //授权头像
        if ($config['yx_lt_new_fan_terms'] && (!$fans['avatar'] || $fans['avatar']!='https://css2020.yixuan.net/2020css/yx2020/images/question.png'))
        {
            $is_new_user = true;
        }
//        if (!$fans['username'] || !$fans['mobile']){
//            $is_new_user = true;
//        }
        return $is_new_user;
    }

    //基础信息检测
    public static function checkBaseError($theme)
    {
        global $_P,$_G,$_S,$_C;
        $error_text = '';
        $now_time = time();
        //
        if (!$_C['is_limit_end_time']){
            if (!$theme) {
                return modelShow(40002);
            }
            if ($theme['begintime']>$now_time) {
                return modelShow(40064);
            }
            if ($now_time>$theme['endtime']) {
                return modelShow(40065);
            }
            if ($theme['status']=='2'){
                return modelShow(40065);
            }
        }else{
            if (!$theme) {
                return modelShow(40002);
            }
            if (TIMESTAMP < $_C['yx_lt_begintime']){
                return modelShow(40064);
            }
            if (TIMESTAMP > $_C['yx_lt_endtime']){
                return modelShow(40065);
            }
        }
        return $error_text;
    }
    //格式化罗盘奖品信息
    public static function getGridList($themeid,$config)
    {
        $list = self::getFontPrizeList($themeid);
        $res = [];
        foreach ($list as $k => $v) {
            $temp_item = [
                'p_id'=>$v['p_id'],
                'title'=>mb_substr($v['title'],0,8),
                'icon'=>$v['small_img'],
                'name'=>$v['name'],
                'amount'=>$v['red_envelopes_amount_max'],
                'desc'=>$v['desc_content'],
                'btn_txt'=>'返回抽奖',
                'type'=>$v['type'],
                'default_type'=>$v['default_type'],
            ];
            array_push($res,$temp_item);
        }
        return $res;
    }
    //获取乱序的前端奖品列表
    public static function getFontPrizeList($themeid)
    {
        $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=".$themeid." and status!=2 ORDER BY  show_sort ASC";
        return db_select($sql);
    }
    //获取抽奖的奖品列表
    public static function getLtPrizeList($themeid)
    {
        $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=".$themeid." AND qty > 0 and status!=2 and pr > 0  ORDER BY  pr ASC";
        return db_select($sql);
    }

    /**
     * Desc:获取当前用户在当前配置下可获取的奖品列表
     * Author:cbw
     * Time: 2023/9/23 14:04
     * @param $themeid
     * @param $uid
     * @param $config
     * @return array[]
     */
    public static function getUserCanGetPrize($themeid,$uid,$config)
    {
        $default_arr = [];
        $bizhiong_arr = [];
        $org_list = self::getLtPrizeList($themeid);//获取当前存在库存、中奖概率的 正常奖项或必中奖
        foreach ($org_list as $k => $v){
            //判断是否已获取奖项
            $has_flag = self::checkUserHasRecordFlag($uid,$themeid,$v['p_id']);
            if ($config['yx_lt_double_flag'] || !$has_flag || $v['default_type']==2){//不存在此奖品奖项或谢谢参与
                //判断每日限额
                if ($v['day_qty']>0){
                    $today_flag = self::getTodayFlag($themeid,$v['p_id']);
                    if ($today_flag<$v['day_qty']){//未达到每日限额
                        if ($v['default_type']==3){//判断必中奖
                            array_push($bizhiong_arr,$v);
                        }else{//判断正常奖项、谢谢参与
                            array_push($default_arr,$v);
                        }
                    }
                }else{
                    if ($v['default_type']==3){//判断必中奖
                        array_push($bizhiong_arr,$v);
                    }else{//判断正常奖项\谢谢参与
                        array_push($default_arr,$v);
                    }
                }
            }
        }

        return ['default_arr'=>$default_arr,'bizhiong_arr'=>$bizhiong_arr];
    }

    //获取未中奖奖项
    public static function getLoseLtPrize($themeid)
    {
        $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid AND default_type=2 ORDER BY pr DESC ";
        return db_find($sql);
    }

    public static function updateAllPrize($where,$data)
    {
        $res = db_update(yx_lt_prize,$data,$where);
    }

    //获取重复性奖项
    public static function getDoubleLrPrize($themeid)
    {
        $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid AND qty>0 AND is_double=1 ORDER BY pr DESC ";
        return db_select($sql);
    }
    //获取必中奖的数量
    public static function getMustPrizeCount($themeid)
    {
        $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid AND qty > 0 AND default_type=3";
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取大库存奖项【正常奖项、必中奖项】
     * Author:cbw
     * Time: 2023/9/23 09:03
     * @param $themeid
     * @return mixed
     */
    public static function getBigQtyPrizeCount($themeid){
        $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid AND total_qty >= 1000 AND default_type!=2";
        return db_find($sql)['cnt'];
    }

    //获取必中奖项
    public static function getMustLtPrize($themeid,$condition="")
    {
        if (!$condition){
            $sql = " SELECT * FROM ".tablename(yx_lt_prize).
                " WHERE themeid=$themeid AND qty > 0 AND default_type=3  ORDER BY pr DESC";
            return db_select($sql);
        }else{
            $sql = " SELECT * FROM ".tablename(yx_lt_prize).
                " WHERE themeid=$themeid AND qty > 0 AND default_type=3".$condition." ORDER BY pr DESC";
            return db_select($sql);
        }

    }

    public static function getMustLtPrizeList($themeid)
    {
        $sql = " select * from ".tablename(yx_lt_prize)." where themeid=$themeid and qty >0 and default_type=3  ORDER BY pr DESC";
        return db_select($sql);
    }

    public static function getAllPrizeQty($themeid)
    {
        $sql = " select sum(qty) as cnt from ".tablename(yx_lt_prize)." where themeid=$themeid";
        return db_find($sql)['cnt'];
    }

    public static function getAllPrizePr($themeid)
    {
        $sql = " select sum(pr) as cnt from ".tablename(yx_lt_prize)." where themeid=$themeid and status=1";
        return db_find($sql)['cnt'];
    }

    //获取用户的已中奖中的必中奖条件
    public static function getUserRecordSql($themeid,$uid)
    {
        $sql = "SELECT b.p_id FROM ".tablename(yx_lt_flag)." AS a LEFT JOIN ".tablename(yx_lt_prize).
            " AS b ON a.p_id = b.p_id and b.themeid=$themeid".
            " WHERE a.themeid=$themeid AND a.uid='{$uid}' and b.default_type=3";
        $res  = db_select($sql);

        $result = '';
        if (!empty($res)) {
            $temp_arr = [];

            foreach ($res as $index=> $item ) {
                if ($index==0) {
                    array_push($temp_arr,$item['p_id']);
                } else {
                    if (!in_array($item['p_id'],$temp_arr)){
                        array_push($temp_arr,$item['p_id']);
                    }
                }
            }

            if (count($temp_arr)==1) {
                $result = " and p_id <> " . $temp_arr[0];
            } else {
                $ids = '';
                foreach ($temp_arr as $key => $val){
                    $ids .=  $val.",";
                }
                $ids = rtrim($ids,',');
                $result = " and p_id not in (" . $ids .")";
            }
        }
        return $result;
    }
    //获取用户是否获得过的查询的奖项中奖记录
    public static function checkUserHasRecordFlag($uid,$themeid,$p_id)
    {
        $sql = "SELECT COUNT(*) AS cnt FROM " . tablename(yx_lt_flag).
            " WHERE uid=".$uid." AND themeid=".$themeid." AND p_id='".$p_id."'";
        return intval(db_find($sql)['cnt']);
    }

    //获取今日奖品的抽中次数
    public static function getTodayFlag($themeid,$p_id)
    {
        $sql = "select count(*) as cnt from ".tablename(yx_lt_flag)." where themeid=$themeid and p_id = $p_id AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
        return intval(db_find($sql)['cnt']);
    }

    //获取用户的已使用抽奖次数
    public static function getUserFlag($uid,$themeid)
    {
        $sql = " select count(*) as cnt from ".tablename(yx_lt_flag)." where uid='{$uid}' and themeid=$themeid";
        return db_find($sql)['cnt'];
    }
    //获取好友助力信息
    public static function getFriendHelpInfo($themeid,$config,$uid,$page_start=0,$page_size=12,$type='friend_view')
    {
        if (empty($uid)){
            return ;
        }
        if ($type=='friend_order'){
            $title ='好友抢购';
        }else{
            if ($type=='friend_view'){
                $title ='好友到访';
            }elseif ($type=='friend_help'){
                $title ='好友助力';
            }
        }
        $top_tips = $config['yx_lt_friend_help_top_tips'];
        if ($type=='friend_order'){
            $top_tips='';
        }

        $btn_txt= '返回';
        $friend_list = self::getFriendHelp($themeid,$uid,0,$page_start,$page_size,$type);
        return [
            'title'=>$title,
            'top_tips'=>$top_tips,
            'friend_list'=>$friend_list,
            'btn_txt'=>$btn_txt
        ];
    }
    //获取好友助力数据
    public static function getFriendHelp($themeid,$uid,$is_today=0,$page_start=0,$page_size = 12,$type='friend_view')
    {
        if (empty($uid)){
            return ;
        }
        $condition = " AND a.uid='{$uid}' and chance>=0 AND type='$type' ORDER BY a.created_at DESC LIMIT ".$page_start.",".$page_size;
        if ($is_today) {
            $condition = " AND a.uid='{$uid}' and chance>=0 AND type='$type' and TO_DAYS(created_at) = TO_DAYS(NOW()) LIMIT ".$page_start.",".$page_size;
        }
        $sql = " SELECT a.*,b.avatar,b.nickname,b.username,b.mobile FROM ".tablename(yx_lt_chance)." AS  a ".
            " LEFT JOIN ".tablename(t_fans)." AS b ON a.from_uid=b.uid and a.themeid=b.themeid".
            " WHERE a.themeid=$themeid".$condition;
        if ($type=='friend_order'){
            $sql = " select avatar,username,nickname from ".tablename(t_record)." where themeid=$themeid and fromuid!=uid and fromuid='$uid' ORDER BY addtime DESC LIMIT ".$page_start.",".$page_size;
        }
        $list =  db_select($sql);
        $res = [];
        foreach ($list as $k => $v) {
            $temp = [
                'avatar'=>$v['avatar'],
                'nickname'=>$v['username']?mb_substr($v['username'],0,6):mb_substr($v['nickname'],0,6)
            ];
            array_push($res,$temp);
        }
        return $res;
    }

    public static function getAllFriendHelpLTotal($themeid,$uid)
    {
        $sql = " select count(*) as cnt from ".tablename(yx_lt_chance)." where themeid=$themeid and uid='{$uid}' and type='friend_view'";
        return db_find($sql)['cnt'];
    }
    //获取红包记录的发放状态
    public static function getRedPackageItemStatus($f_id,$themeid,$uid)
    {
        $sql = " select a.f_id,a.p_id,a.themeid,a.status as red_status,b.status from ".tablename(yx_lt_rp_flag)." as a ".
            " LEFT JOIN ".tablename(t_comm)." AS b ON a.tc_id=b.id and b.themeid=$themeid".
            " WHERE a.themeid=$themeid AND a.uid='{$uid}' and a.f_id=$f_id";
        return db_find($sql);
    }

    //获取奖品信息
    public static function getMyPrizeInfo($themeid,$config,$uid)
    {
        $fans = self::getUserInfoById($uid,$themeid);
        $btm_txt='继续抽奖';
        $red_package_amount = $fans['new_rp_amount'];
        $red_package_min_amount = $config['red_package_min_amount'];
        $can_get = 0;
        if ($red_package_amount>=$red_package_min_amount) {
            $can_get = 1;
        }
        $red_package_flag_total = self::getUserWithDrawAmount($themeid,$uid);
        $red_package_info = [
            'icon'=>$config['red_package_icon'],
            'amount'=>(float)$fans['new_rp_amount'],
            'total_amount'=>(float)$red_package_flag_total,
            'btm_tips'=>$config['red_package_btm_tips'],
            'can_get'=>$can_get,//能否提现
            'btn_txt'=>$fans['new_rp_amount']>0?$config['red_package_right_btn_txt']:'全部已提现'
        ];

        $list = self::getUserPrizeList($themeid,$uid,$page_start=0,$page_size=10);
        $prize_info = [];
        if (!empty($list)){
            foreach ($list as $k =>$v) {
                if ($v['from_type']=='red_envelope'){
                    $item = LotteryModel::getRpFlagItem(['themeid'=>$themeid,'f_id'=>$v['f_id']]);
                    if ($item && $v['red_envelopes_amount_min']!=$v['red_envelopes_amount_max']){
                        $v['title'] = '红包'.$item['amount'].'元';
                    }
                }
                if ($v['p_id']!=0){
                    //判断我的奖品中是否存在已兑换的奖品
//                    if (!$config['yx_lt_convert_only'] && $v['status']==3){
//                        //其他相同奖品失效
////                        self::editUserLtFlagLose($uid,$themeid,$v['p_id'],$v['f_id']);
//                    }
                    $temp = [
                        'img'=>$v['small_img'],
                        'f_id'=>$v['f_id'],
                        'convert_code'=>$v['convert_code'],
                        'name'=>$v['name'],
                        'title'=>$v['title'],
                        'status'=>$v['status'],
                        'default_type'=>$v['default_type'],
                        'type'=>$v['type'],
                        'btn_txt'=>self::getLtFlagType($v['status']),
                        'time'=>$v['created_at']
                    ];
//                    $prize_info[$v['f_id']] = $temp;
                    $prize_info[] = $temp;
                }
            }
        }
        return [
            'red_package_info'=>$red_package_info,
            'prize_info'=>$prize_info,
            'btm_txt'=>$btm_txt
        ];
    }

    //获取用户的中奖记录
    public static function getUserPrizeList($themeid,$uid,$page_start=0,$page_size=10)
    {
        if (empty($uid)){
            return ;
        }
        $condition = " ORDER BY a.created_at DESC ";
        if ($page_size>0){
            $condition .= " LIMIT ".$page_start.",".$page_size;
        }
        $sql = " SELECT a.*,c.name,c.title,c.small_img,c.default_type,c.type,c.red_envelopes_amount_min,c.red_envelopes_amount_max FROM ".tablename(yx_lt_flag)." AS  a ".
            " LEFT JOIN ".tablename(yx_lt_prize)." AS c ON a.p_id=c.p_id and c.themeid=$themeid".
            " WHERE a.themeid=$themeid AND a.uid='{$uid}'".$condition;
        return db_select($sql);
    }
    //获取中奖记录的类型文字
    public static function getLtFlagType($code)
    {
        $txt = '';
        switch ($code) {
            case 1:
                $txt = '待领取';
                break;
            case 2:
                $txt = '已失效';
                break;
            case 3:
                $txt = '待核销';
                break;
            case 4:
                $txt = '已核销';
                break;
            default:
                break;
        }
        return $txt;
    }
    //获取中奖记录
    public static function getRecordList($themeid,$config,$nickname,$is_index=false)
    {
        $fakelottery = $config['yx_lt_dummy'];
        $show_pr_total = self::checkShowPrItems($themeid);//获取前台展示占比的奖项的数量

        if ($show_pr_total>0) {
            $real_flag = (int)$show_pr_total;
        } else {
            //获取真实用户的一次中奖记录 求总和
            $real_flag = (int)self::getRealUserRecords(0,$themeid);
        }

        if ($show_pr_total>0) {
            if ($real_flag>0) {
                $lt_info = self::getUserRecords(0,$themeid,4);
                $lt_str = '';
                foreach ($lt_info as $key =>$val) {
                    $lt_str .= $val['p_id'].',';
                }
                $lt_str = rtrim($lt_str,',');
                $flag_list = self::getUserInfoAndLtItemByLttId($lt_str,$themeid);
            } else {
                $flag_list= [];
            }
        } else {
            if ($real_flag>0) {
                $lr_info = self::getUserRecords(0,$themeid,2,$real_flag);
                $lr_str = "";
                foreach ($lr_info as $key =>$val) {
                    $lr_str .= $val['f_id'].',';
                }
                $lr_str = rtrim($lr_str,',');
                $flag_list = self::getUserInfoAndLtItemByLrId($lr_str,$themeid);
            } else {
                $flag_list = [];
            }
        }

        if (!empty($flag_list)){
            foreach ($flag_list  as $key => $row){
                if ($row['status']=="-1"){
                    $flag_list[$key]['nickname']=$row['xn_nickname'];
                    $flag_list[$key]['username']=$row['xn_username'];
                    $flag_list[$key]['mobile']=$row['xn_mobile'];
                    $flag_list[$key]['avatar']=$row['xn_avatar'];
                }
            }
            shuffle($flag_list);
        }

        if (!empty($flag_list)) {
            foreach ($flag_list as $k => $v) {
                if ($v['from_type']=='red_envelope'){
                    $flag_list[$k]['title'] = '红包'.$v['red_envelopes_amount_max'].'元';
                }
                if (!empty($flag_list[$k]['username'])) {
                    $flag_list[$k]['username'] = substr_cut_username($v['username']);
                } else {
                    $flag_list[$k]['username'] = substr_cut_username($v['nickname']);
                }
                $flag_list[$k]['tips'] = '获得'.$flag_list[$k]['title'];
                $flag_list[$k]['icon'] = '';
                if (strlen($flag_list[$k]['created_at'])<11){

                    if (strstr($config['softtag0'],"婚纱")!==false ){
                        $kaishishu = intval( substr(MODULE_NAME, -1))%7*30+730+3*date('H');
                    }else{
                        $kaishishu = intval( substr(MODULE_NAME, -1))%10*40+10*date('H');
                    }
                    //取昵称中的第一位根据ascii码算得秒数
                    $nickname = mb_substr($v['username'],0,1,'utf-8');
                    $nickname = mb_convert_encoding($nickname, 'GBK');

                    $miao = ord($nickname) % 60;

                    //取昵称中的第一位根据ascii码算得分钟数
                    $nickname = mb_substr($v['username'],1,1,'utf-8');
                    $nickname = mb_convert_encoding($nickname, 'GBK');
                    $fen = ord($nickname) % 60;

                    //取当前时间计算小时数
                    $xiaoshi = date('H')-7;
                    if ($xiaoshi<0){
                        $created_at=date("Y-m-d",'-1 day');
                        $xiaoshi = 12;
                    }else{
                        $created_at=date("Y-m-d");
                    }
                    if ($xiaoshi==0){
                        $xiaoshi = 1;
                    }
                    $xiaoshi = $xiaoshi==0?7:ord($nickname) % $xiaoshi + 7;
                    if ($xiaoshi<10){ $xiaoshi = "0".$xiaoshi;}
                    if ($fen<10){ $fen = "0".$fen;}
                    if ($miao<10){ $miao = "0".$miao;}
                    $created_at = $created_at ." " .$xiaoshi .":".$fen.":".$miao;
//                    if (time()>$config['yx_lt_endtime']){
//                        $end_time = $config['yx_lt_endtime'];
//                    }else{
//                        $end_time = time();
//                    }
//                    $rand_time = randomDate($config['yx_lt_begintime'],$end_time);
////                    $flag_list[$k]['created_at'] = date("Y-m-d",strtotime($flag_list[$k]['created_at']));
                    $flag_list[$k]['created_at'] = $created_at;
                }else{
                    $flag_list[$k]['created_at'] = date("Y-m-d H:i:s",strtotime($flag_list[$k]['created_at']));
                }

            }
        }
        array_multisort(array_column($flag_list,'created_at'),SORT_DESC,$flag_list);
        if ($config['yx_lt_show_flag_method']==1 && $is_index){
            return [];
        }
        return $flag_list;
        //后20条虚拟 前面为真实

    }
    //获取展示占比大于0 的奖项数量
    public static function checkShowPrItems($themeid)
    {
        $sql = " SELECT COUNT(*) AS cnt FROM " .tablename(yx_lt_prize)." WHERE themeid=$themeid AND show_pr >0";
        return db_find($sql)['cnt'];
    }
    //获取所有用户的中间记录数
    public static function getRealUserRecords($uid,$themeid)
    {
        $condition = " where";
        if ($uid!=0) {
            $condition = " where uid=". $uid." and";
        }
        $sql = " SELECT * FROM " . tablename(yx_lt_flag) . $condition.
            " themeid=".$themeid."  GROUP BY uid";
        $user_flag = db_select($sql);
        return count($user_flag);
    }
    //获取中奖记录数
    public static function getUserRecords($uid,$themeid,$type=1,$limit=10)
    {
        if ($type==1) {
            $condition = " WHERE";
            if ($uid!=0) {
                $condition = " WHERE uid=". $uid." AND";
            }
            $sql = "SELECT COUNT(*) AS cnt FROM " . tablename(yx_lt_flag) . $condition.
                " themeid=".$themeid."  GROUP BY uid";
            $user_flag = intval(db_find($sql)['cnt']);//中奖奖记录数
        }
        if ($type==3) {
            $sql = "SELECT COUNT(*) FROM (SELECT * FROM " .tablename(yx_lt_flag) ." WHERE themeid =".$themeid.
                " GROUP BBY uid ) AS a";
            $user_flag = (int)db_fetchcolumn($sql);
        }
        if ($type==2) {
            $sql = "SELECT * FROM " .tablename(yx_lt_flag) ." WHERE themeid =".$themeid.
                " and from_type!=2 GROUP BY uid ORDER BY created_at DESC limit ".$limit;
            $user_flag = db_select($sql);
        }
        if ($type==4) {
            $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid AND show_pr >0 and default_type!=2 ORDER BY show_pr DESC limit ".$limit;
            $user_flag = db_select($sql);
        }
        return $user_flag;
    }
    //通过中奖记录ids获取中奖机会信息以及用户信息
    public static function getUserInfoAndLtItemByLrId($lr_ids,$themeid)
    {
        $sql = "SELECT a.from_type,a.created_at,b.username,b.nickname,b.avatar,c.title,c.name,c.red_envelopes_amount_min,c.red_envelopes_amount_max FROM ".tablename(yx_lt_flag).
            " AS a LEFT JOIN". tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(yx_lt_prize)." AS c ON a.p_id=c.p_id and c.themeid=$themeid".
            " WHERE a.f_id in( ". $lr_ids." ) AND b.nickname is not null AND b.avatar is not null AND b.nickname <>'' AND b.avatar <> '' and a.created_at < NOW() ORDER BY a.created_at DESC limit 50";
        return db_select($sql);
    }
    //通过奖项ids获取中奖记录
    public static function getUserInfoAndLtItemByLttId($p_ids,$themeid)
    {
        $sql = "SELECT a.uid,a.from_type,a.created_at,a.status,b.username,b.nickname,b.avatar,c.title,c.name,c.red_envelopes_amount_min,c.red_envelopes_amount_max,
            d.username as xn_username,d.nickname as xn_nickname,d.avatar as xn_avatar,d.mobile as xn_mobile FROM ".tablename(yx_lt_flag).
            " AS a LEFT JOIN". tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
            " LEFT JOIN ".tablename(yx_lt_prize)." AS c ON a.p_id=c.p_id and c.themeid=$themeid".
            " LEFT JOIN ".tablename(t_2019fans)." AS d ON a.uid=d.id ".
            " WHERE a.p_id in( ". $p_ids." )  and a.created_at < NOW() ORDER BY a.created_at DESC limit 50";
        return db_select($sql);
    }
    //获取指定数量的虚拟用户头像和昵称
    public static  function  getVirtualUserInfo($nickname,$limit,$config,$themeid,$pids='',$start_time='',$ned_time = '')
    {
        if (strstr($config['softtag0'],"婚纱")!==false ){
            $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+1045;
        }else{
            $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+2545;
        }
        $theme = Theme::getThemeById($themeid);
        //获取虚拟中奖记录最后一条
        $tmp_sql = " select uid from ".tablename(yx_lt_flag)." where themeid=$themeid and status=-1 order by f_id desc";
        $virtual_last = db_find($tmp_sql);
        if ($virtual_last){
            $kaishishu = $virtual_last['uid'];
        }
        $xunisql = self::getXuniSql($nickname,$limit,$config,$kaishishu);
        $res = db_select($xunisql);
        if (!$res){
            if (strstr($config['softtag0'],"婚纱")!==false ){
                $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+1045;
            }else{
                $kaishishu = intval( substr(MODULE_NAME, -3))%30*45+2545;
            }
            $xunisql = self::getXuniSql($nickname,$limit,$config,$kaishishu);
            $res = db_select($xunisql);
        }
        $show_ratiio_total = (int)self::checkShowPrItems($themeid);//获取前台展示占比的奖项的数量
        if ($show_ratiio_total<0) {
            $res = self::getListShowRatiioItems($res,$themeid,$pids,$start_time,$ned_time);
        } else {
            $res = self::getListShowRatiioItems($res,$themeid,$pids,$start_time,$ned_time);
        }
        return $res;
    }
    public static function getXuniSql($nickname,$limit,$config,$kaishishu)
    {
        if ($config['touxiang']==0) {
            if ($nickname){
                $xunisql = "SELECT id as uid FROM " . tablename(t_2019fans) .
                    " WHERE id >". $kaishishu ." and nickname!='".$nickname."' and avatar!=''  LIMIT $limit";
            }else{
                $xunisql = "SELECT id as uid FROM " . tablename(t_2019fans) .
                    " WHERE id >". $kaishishu ." and avatar!=''  LIMIT $limit";
            }

        } else {
            if ($nickname){
                $xunisql = "SELECT id as uid FROM " . tablename(t_2019fans) .
                    " WHERE id >". $kaishishu ." and nickname!='".$nickname."' and avatar!='' LIMIT $limit";
            }else{
                $xunisql = "SELECT id as uid FROM " . tablename(t_2019fans) .
                    " WHERE id >". $kaishishu ." and avatar!='' LIMIT $limit";
            }
        }
        return $xunisql;
    }

    //虚假用户获取 获取固定的中奖奖项key
    public static function getRoundLtItem($themeid,$id)
    {
        $sql = "SELECT title,type,red_envelopes_amount_max FROM ".tablename(yx_lt_prize)." WHERE pr>1 and default_type!=2 AND themeid=".$themeid;
        $list = db_select($sql);
        $total = count($list);
        $last_str = (int)substr($id,-1);
        if ($total>0){
            if ($last_str<=$total-1) {
                return $list[$last_str];
            } else {
                $key = ceil($last_str % $total);
                return $list[$key];
            }
        }
    }

    //虚拟中奖记录根基前台展示占比随机生成
    public static function getListShowRatiioItems($list,$themeid,$pids='',$start_time='',$ned_time = '')
    {
        $max_num = count($list);
        $eq_show_list = self::getShowRatiioItems($themeid,$pids);
        $temp_total_show_pr = (int)self::getShowRatiioTotalShowPr($themeid,$pids);

        $eq_show_total = count($eq_show_list);

        if ($eq_show_total>0) {
            //存在展示占比奖项
            $show_items = [];
            $show_items_num = 0;
            foreach ($eq_show_list as $k => $val) {
                if ($val['type']=='red_envelope'){
                    if ($val['red_envelopes_amount_max']){
                        $val['title'] = '红包'.$val['red_envelopes_amount_max'].'元';
                    }
                }
                $show_item = [];
                $show_item['title'] = $val['title'];
                $show_item['p_id'] = $val['p_id'];
                $show_item['total'] = (int)floor(($val['show_pr']/$temp_total_show_pr)*count($list));
                $show_items_num += $show_item['total'];
                array_push($show_items,$show_item);
            }

            if ($show_items_num < $max_num) {
                foreach ($show_items as $key =>$v) {
                    if (($v['total']+1)<$max_num && $show_items_num < $max_num) {
                        $show_items[$key]['total'] +=1;
                        $show_items_num+=1;
                    }
                }
            }
            $diff = $max_num-$show_items_num;
            $round_key = round(0,$eq_show_total-1);
            $show_items[$round_key]['total'] +=$diff;

            $first_arr = [];
            foreach ($list as $kk => $vv) {
                $temp_arr = [];
                $temp_arr['key']=$kk;
                array_push($first_arr,$temp_arr);
            }
            foreach ($show_items as $dd =>$ff) {
                for ($i=1;$i<=$ff['total'];$i++) {
                    $first_round = (int)round(0,count($first_arr)-1);
                    $temp_key = $first_arr[$first_round]['key'];
                    $list[$temp_key]['p_id'] = $ff['p_id'];
                    $list[$temp_key]['from_type'] = 'default';
                    $list[$temp_key]['convert_code'] = '';
                    $list[$temp_key]['workerid'] = 0;
                    $list[$temp_key]['status'] = -1;
                    $list[$temp_key]['themeid'] = $themeid;
                    array_splice($first_arr,$first_round,1);
                }
            }
            shuffle($list);
            foreach ($list as $kkk => $vvv){
                $rand_time = self::randTimes($start_time,$ned_time,true,count($list));
                $list[$kkk]['created_at'] = $rand_time[$kkk];
            }
        }
        $all_sql = " ";
        foreach ($list as $kk => $vv){
            $tmp_str = "(";
            $tmp_str .= "'".$vv['uid']."',";
            $tmp_str .= "'".$vv['from_type']."',";
            $tmp_str .= "'".$vv['convert_code']."',";
            $tmp_str .= "'".$vv['p_id']."',";
            $tmp_str .= "'".$vv['workerid']."',";
            $tmp_str .= "'".$vv['status']."',";
            $tmp_str .= "'".$vv['themeid']."',";
            $tmp_str .= "'".$vv['created_at']."'),";
            $all_sql .= $tmp_str;
        }
        $all_sql = rtrim($all_sql,",");

        return self::insertAllVirtual($all_sql);
    }

    static function insertAllVirtual($all_sql)
    {
        $sql = " INSERT INTO ".tablename(yx_lt_flag)." (uid,from_type,convert_code,p_id,workerid,status,themeid,created_at) VALUES ".
            $all_sql;
        return \think\Db::execute($sql);
    }

    static function randTimes($startime, $endtime,$is = true,$num = 5)
    {
        $i=0;
        $begin = strtotime($startime);
        $end = strtotime($endtime);
        $array = array();
        while ($i < $num){
            $date = rand($begin, $end);
            $array[] = $is ? date("Y-m-d H:i:s",$date) : $date;
            $i++;
        }
        sort($array);
        return $array;
    }
    //获取展示比例 降序 list
    public static function getShowRatiioItems($themeid,$pids='')
    {
        if ($pids){
            $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid and p_id in $pids  AND show_pr >0 and default_type!=2 ORDER BY show_pr DESC";
        }else{
            $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid AND show_pr >0 and default_type!=2 ORDER BY show_pr DESC";
        }

        $res = db_select($sql);
        return $res;
    }

    public static function getShowRatiioTotalShowPr($themeid,$pids='')
    {
        if ($pids){
            $sql = " SELECT sum(show_pr) as total_show_pr FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid and p_id in $pids AND show_pr >0 and default_type!=2 ORDER BY show_pr DESC";
        }else{
            $sql = " SELECT sum(show_pr) as total_show_pr FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid AND show_pr >0 and default_type!=2 ORDER BY show_pr DESC";
        }
        return db_find($sql)['total_show_pr'];
    }
    
    public static function getTotalShowPr($themeid)
    {
        $sql = " select sum(show_pr) as total_show_pr from ".tablename(yx_lt_prize)." where themeid=$themeid";
        return db_find($sql)['total_show_pr'];
    }
    //获取抽奖攻略
    public static function getLotteryMethod($uid,$themeid,$config,$has_order=false,$is_index = false)
    {
        $fans = self::getUserInfoById($uid,$themeid);
        $user_lt_num = $fans['jihui'];
        $max_lt_num = $config['yx_lt_chance_limit'];
        $list = [];

        $btnTxt2 = '已完成';
        $status2 = 2;
        $btnTxt1 = '去完成';
        $status1 = 1;
        $btnTxt3 = '到上限';
        $status3 = 3;


        //self_order
        $has_self_order = self::getUserRecordsByType($uid,'self_order',$themeid);
        if ($config['yx_lt_self_order']>0) {
            $tips_1 = '您自己下单抢购增加'.$config['yx_lt_self_order'].'次抽奖机会';
            $btn_1 = $btnTxt1;
            $status_1 = $status1;
            if ($has_self_order>0) {
                $btn_1 = $btnTxt2;
                $status_1 = $status2;
            }
            $temp_1 = ['title'=>'下单抢购','icon'=>$_G['URL']['PLUGIN_CSS']."lottery/images/icon3.png",'num'=>'+'.$config['yx_lt_self_order'],
                'tips'=>$tips_1,'status'=>$status_1,'btn_txt'=>$btn_1,'type'=>'order','timeset'=>'','other_id'=>''
            ];
        }
        //friend_order
        $has_friend_order = self::getUserRecordsByType($uid,'friend_order',$themeid);
        if ($config['yx_lt_friend_order']>0) {
            $tips_2 = '好友通过您分享的链接下单抢购，您增加'.$config['yx_lt_friend_order'].'次抽奖机会';
            if ($config['yx_lt_main_order']){
                $tips_2 = '您自己下单抢购后，'.$tips_2;
            }
            $btn_2 = $btnTxt1;
            $status_2 = $status1;
            if ($has_friend_order>0) {
                $btn_2 = $btnTxt2;
                $status_2 = $status2;
            }
            $temp_2 = ['title'=>'好友抢购','icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon4.png','num'=>'+'.$config['yx_lt_friend_order'],
                'tips'=>$tips_2,'status'=>$status_2,'btn_txt'=>$btn_2,'type'=>'share','timeset'=>'','other_id'=>''
            ];
        }
        //share_moments
        $first_day = (int)$config['yx_lt_first_share_moment'];
        $second_day = (int)$config['yx_lt_second_share_moment'];
        $third_day = (int)$config['yx_lt_third_share_moment'];
        $all_moments = $first_day+$second_day+$third_day;

        //判断分享朋友圈的限制条件
        $can_moment_method = true;
        $config_share_moment = $config['yx_lt_share_moment_user_type'];
        if ($config_share_moment) {
            if (!$has_order) {
                $can_moment_method = false;
            }
        }
        if ($all_moments>0) {
            $num = 0;
            $today_flag = self::getUserRecordsByType($fans['uid'],'share_moments',$themeid,true);//朋友圈今日记录
            $moments = self::getUserRecordsByType($fans['uid'],'share_moments',$themeid);

            if ($moments==0) {
                if ($first_day){
                    $num = $first_day;
                }else{
                    $num = 1;
                }

            } elseif ($moments==1) {
                if ($second_day){
                    $num = $second_day;
                }else{
                    $num = 1;
                }

            } elseif ($moments==2) {
                if ($third_day){
                    $num = $third_day;
                }else{
                    $num = 1;
                }
            }

            if (($today_flag>=1 && $num>0)) {
                $num = 1;
            }
            $tips_3_pre = '';
            if ($config_share_moment && !$can_moment_method){
                //需支付才满足 当前用户未支付
                $tips_3_pre = '下单后';
            }
            $tips_3= $tips_3_pre."将链接分享到朋友圈";
            if ($first_day>0) {
                $tips_3.="，第1天增加". $first_day. "次抽奖机会";
            }
            if ($second_day>0) {
                $tips_3.="，第2天增加". $second_day. "次机会";
            }
            if ($third_day>0) {
                $tips_3.="，第3天增加". $third_day. "次机会";
            }

            if ($moments <=2) {
                if ($today_flag>=1 && $num >0) {
                    $title = '分享朋友圈今日已完成';
                    $status_3 = $status2;
                    $btn_3 = $btnTxt2;
                } elseif ($today_flag<1 && $num >0) {
                    $title = '分享到朋友圈';
                    $status_3 = $status1;
                    $btn_3 = $btnTxt1;
                }
                if ($title) {
                    if ($today_flag>=1){
                        if ($moments==1){
                            $num = $first_day;
                        }elseif ($moments==2){
                            $num = $second_day;
                        }elseif ($moments==3){
                            $num = $third_day;
                        }
                        $temp_3 = ['title'=>$title,'icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon5.png','num'=>'+'.$num,
                            'tips'=>$tips_3,'status'=>$status_3,'btn_txt'=>$btn_3,'type'=>'share_moments','timeset'=>'','other_id'=>''
                        ];
                    }else{
                        $temp_3 = ['title'=>$title,'icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon5.png','num'=>'+'.$all_moments,
                            'tips'=>$tips_3,'status'=>$status_3,'btn_txt'=>$btn_3,'type'=>'share_moments','timeset'=>'','other_id'=>''
                        ];
                    }

                } else {
                    $temp_3 = ['title'=>'分享朋友圈','icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon5.png','num'=>'+'.$all_moments,
                        'tips'=>$tips_3,'status'=>$status_3,'btn_txt'=>$btn_3,'type'=>'share_moments','timeset'=>'','other_id'=>''
                    ];
                }
            } else {
                $temp_3 = ['title'=>'分享朋友圈','icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon5.png','num'=>'+'.$all_moments,
                    'tips'=>$tips_3,'status'=>$status2,'btn_txt'=>$btnTxt2,'type'=>'share_moments','timeset'=>'','other_id'=>''
                ];
            }
        }
        //friend_view
        if ($config['yx_lt_friend_view']>0) {
            $title4 = '每邀请'.$config['yx_lt_friend_view'].'人到访';
            $tips_4 = '邀请越多好友，获得越多奖励,最多获得'.$config['yx_lt_friend_view_limit'].'次机会';
            if ($config['yx_lt_view_user_type']==1){
                $tips_4 = '购买后，'.$tips_4;
                $title4= '购买后，'.$title4;
            }
            $temp_4 = ['title'=>$title4,'icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon6.png','num'=>'+1',
                'tips'=>$tips_4,'status'=>$status1,'btn_txt'=>'去邀请','type'=>'helpFriend','timeset'=>'','other_id'=>''
            ];
        }
        //timeset
        if ($config['yx_lt_timeset']>0) {
            $status5 = 1;
            $btn5 = '后领取';
            $other_id = '';
            $timeset = date('Y-m-d H:i:s', strtotime('+'.$config['yx_lt_timeset']." ".'hour'));

            //判断当前是否有进行中的记录
            $has_process_receive = self::getLastWaitFlag($uid,$themeid,1);
            if ($has_process_receive) {
                $new_time = time();
                $get_at = strtotime($has_process_receive['get_at']);
                if ($get_at<$new_time) {
                    $other_id = $has_process_receive['t_id'];
                    $status5 = 4;
                    $timeset = '去领取';
                    $btn5 = '去领取';
                } else {
                    $other_id = $has_process_receive['t_id'];
                    $btn5 = '后领取';
                    $timeset =$has_process_receive['get_at'];
                }
            }else{
                //判断今日是否有定时领取记录
                $has_timeset_flag = self::getNoReceiveTypeFlag($uid,$themeid,0);
                if (!$has_timeset_flag) {
                    if ($config['yx_lt_timeset_user_type']){
//                        $themyrecord = Record::getLastGroupByUid($uid,$themeid);
                        $themyrecord = db_get(t_record,['uid'=>$uid,'themeid'=>$themeid,'status >'=>0]);
                        if ($themyrecord){
                            //判断总数
                            $limit = (int)$config['yx_lt_timeset_limit'];
                            $has_flag_total = (int)self::getTimeFlagTotal($uid,$themeid);
                            if ($has_flag_total+1<=$limit){
                                $insert_data = [
                                    'uid'=>$uid,
                                    'get_at'=>date('Y-m-d H:i:s', strtotime('+'.$config['yx_lt_timeset'].'hour')),
                                    'status'=>1,
                                    'themeid'=>$themeid
                                ];
                                self::insertTimeSetItem($insert_data);
                                $has_process_receive = self::getLastWaitFlag($uid,$themeid,1);
                                if ($has_process_receive){
                                    $new_time = time();
                                    $get_at = strtotime($has_process_receive['get_at']);
                                    if ($get_at<$new_time) {
                                        $other_id = $has_process_receive['t_id'];
                                        $status5 = 4;
                                        $timeset = '';
                                        $btn5 = '去领取';
                                    } else {
                                        $other_id = $has_process_receive['t_id'];
                                        $btn5 = '后领取';
                                        $timeset =$has_process_receive['get_at'];
                                    }
                                }
                            }else{
                                $status5 = $status3;
                                $btn5 = $btnTxt3;
                                $timeset = '';
                            }
                        }
                    }else{
                        //判断总数
                        $limit = (int)$config['yx_lt_timeset_limit'];
                        $has_flag_total = (int)self::getTimeFlagTotal($uid,$themeid);
                        if ($has_flag_total+1<=$limit){
                            $insert_data = [
                                'uid'=>$uid,
                                'get_at'=>date('Y-m-d H:i:s', strtotime('+'.$config['yx_lt_timeset'].'hour')),
                                'status'=>1,
                                'themeid'=>$themeid
                            ];
                            self::insertTimeSetItem($insert_data);
                            $has_process_receive = self::getLastWaitFlag($uid,$themeid,1);
                            if ($has_process_receive){
                                $new_time = time();
                                $get_at = strtotime($has_process_receive['get_at']);
                                if ($get_at<$new_time) {
                                    $other_id = $has_process_receive['t_id'];
                                    $status5 = 4;
                                    $timeset = '';
                                    $btn5 = '去领取';
                                } else {
                                    $other_id = $has_process_receive['t_id'];
                                    $btn5 = '后领取';
                                    $timeset =$has_process_receive['get_at'];
                                }
                            }
                        }else{
                            $status5 = $status3;
                            $btn5 = $btnTxt3;
                            $timeset = '';
                        }
                    }

                }
            }

            $tips_5 = '每日首次登陆'.$config['yx_lt_timeset'].'小时后，送1次机会';
            $temp_5 = ['title'=>'定时奖励','icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon7.png','num'=>'+1',
                'tips'=>$tips_5,'status'=>$status5,'btn_txt'=>$btn5,'type'=>'timeset','timeset'=>$timeset,'other_id'=>$other_id
            ];
        }
        //friend_help
        if ($config['yx_lt_friend_help']>0){
            $title6 = '每邀请'.$config['yx_lt_friend_help'].'人助力';
            $tips_6 = '邀请越多好友助力，获得越多奖励,最多获得'.$config['yx_lt_friend_help_limit'].'次机会';
            if ($config['yx_lt_help_user_type']==1){
                $tips_6 = '购买后，'.$tips_6;
                $title6= '购买后，'.$title6;
            }
            $temp_6 = ['title'=>$title6,'icon'=>$_G['URL']['PLUGIN_CSS'].'lottery/images/icon6.png','num'=>'+1',
                'tips'=>$tips_6,'status'=>$status1,'btn_txt'=>'去邀请','type'=>'friendHelp','timeset'=>'','other_id'=>''
            ];
        }
        //判断用户的抽奖机会是否达到上限
        if ($temp_1) {
            if ($user_lt_num>=$max_lt_num) {
                $temp_1['status']=$status3;
                $temp_1['btn_txt']=$btnTxt3;
            }
            array_push($list,$temp_1);
        }
        if ($temp_2) {
            if ($user_lt_num>=$max_lt_num) {
                $temp_2['status']=$status3;
                $temp_2['btn_txt']=$btnTxt3;
            }
            array_push($list,$temp_2);
        }
        if ($temp_3) {
            if ($user_lt_num>=$max_lt_num) {
                $temp_3['status']=$status3;
                $temp_3['btn_txt']=$btnTxt3;
            }
            array_push($list,$temp_3);
        }
        if ($config['yx_lt_timeset_user_type']){
//            $themyrecord = Record::getLastGroupByUid($uid,$themeid);
            $themyrecord = db_get(t_record,['uid'=>$uid,'themeid'=>$themeid,'status >'=>0]);
            if ($themyrecord){
                if ($temp_5) {
                    if ($user_lt_num>=$max_lt_num) {
                        $temp_5['status']=$status3;
                        $temp_5['btn_txt']=$btnTxt3;
                        $temp_5['timeset']='';
                    }
                    array_push($list,$temp_5);
                }
            }
        }else{
            if ($temp_5) {
                if ($user_lt_num>=$max_lt_num) {
                    $temp_5['status']=$status3;
                    $temp_5['btn_txt']=$btnTxt3;
                    $temp_5['timeset']='';
                }
                array_push($list,$temp_5);
            }
        }
        if ($config['yx_lt_view_user_type']){
//            $themyrecord = Record::getLastGroupByUid($uid,$themeid);
//            if ($themyrecord){
//                if ($temp_4) {
//                    if ($user_lt_num>=$max_lt_num) {
//                        $temp_4['status']=$status3;
//                        $temp_4['btn_txt']=$btnTxt3;
//                    }
//                    //处理好友到访的数量上限
//                    $set_lotteryview = $config['yx_lt_friend_view'];
//                    $flag_num = self::getUserRecordsByType($fans['uid'],'friend_view',$themeid);
//                    if(is_int($flag_num/$set_lotteryview) && ($flag_num/$set_lotteryview)>$config['yx_lt_friend_view_limit']){
//                        $temp_4['status']=$status3;
//                        $temp_4['btn_txt']=$btnTxt3;
//                    }
//                    array_push($list,$temp_4);
//                }
//            }
            if ($temp_4) {
                if ($user_lt_num>=$max_lt_num) {
                    $temp_4['status']=$status3;
                    $temp_4['btn_txt']=$btnTxt3;
                }
                //处理好友到访的数量上限
                $set_lotteryview = $config['yx_lt_friend_view'];
                $flag_num = self::getUserRecordsByType($fans['uid'],'friend_view',$themeid);
                if(is_int($flag_num/$set_lotteryview) && ($flag_num/$set_lotteryview)>$config['yx_lt_friend_view_limit']){
                    $temp_4['status']=$status3;
                    $temp_4['btn_txt']=$btnTxt3;
                }
                array_push($list,$temp_4);
            }
        }else{
            if ($temp_4) {
                if ($user_lt_num>=$max_lt_num) {
                    $temp_4['status']=$status3;
                    $temp_4['btn_txt']=$btnTxt3;
                }
                //处理好友到访的数量上限
                $set_lotteryview = $config['yx_lt_friend_view'];
                $flag_num = self::getUserRecordsByType($fans['uid'],'friend_view',$themeid);
                if(is_int($flag_num/$set_lotteryview) && ($flag_num/$set_lotteryview)>=$config['yx_lt_friend_view_limit']){
                    $temp_4['status']=$status3;
                    $temp_4['btn_txt']=$btnTxt3;
                }
                array_push($list,$temp_4);
            }
        }
//        好友助力
        if ($config['yx_lt_friend_help_limit']){
            if ($temp_6){
                if ($user_lt_num>=$max_lt_num) {
                    $temp_6['status']=$status3;
                    $temp_6['btn_txt']=$btnTxt3;
                }
                //处理好友到访的数量上限
                $set_lotteryhelp = $config['yx_lt_friend_help'];
                $flag_num = self::getUserRecordsByType($fans['uid'],'friend_help',$themeid);
                if(is_int($flag_num/$set_lotteryhelp) && ($flag_num/$set_lotteryhelp)>$config['yx_lt_friend_help_limit']){
                    $temp_6['status']=$status3;
                    $temp_6['btn_txt']=$btnTxt3;
                }
                array_push($list,$temp_6);
            }
        }else{
            if ($temp_6) {
                if ($user_lt_num>=$max_lt_num) {
                    $temp_6['status']=$status3;
                    $temp_6['btn_txt']=$btnTxt3;
                }
                //处理好友到访的数量上限
                $set_lotteryhelp = $config['yx_lt_friend_help'];
                $flag_num = self::getUserRecordsByType($fans['uid'],'friend_help',$themeid);
                if(is_int($flag_num/$set_lotteryhelp) && ($flag_num/$set_lotteryhelp)>$config['yx_lt_friend_help_limit']){
                    $temp_6['status']=$status3;
                    $temp_6['btn_txt']=$btnTxt3;
                }
                array_push($list,$temp_6);
            }
        }

        if ($config['yx_lt_show_flag_method']==1 && $is_index){
            return [];
        }

        return $list;
    }
    //获取当前用户的各种类型的增加抽奖次数的记录
    public static function getUserRecordsByType($uid,$type,$themeid,$check_today=false)
    {
        if (empty($uid)){
            return ;
        }
        if ($type){
            $condition = " WHERE type='".$type."' AND uid=".$uid." AND themeid=".$themeid;
        }elseif ($type=='used'){
            $condition = " WHERE chance < 0 AND uid=".$uid." AND themeid=".$themeid;
        }else{
            $condition = " WHERE chance > 0  AND uid=".$uid." AND themeid=".$themeid;
        }

        if ($check_today) {
            $today = date("Y-m-d",time());
            $condition .= " AND date="."'".$today."'";
        }
        $sql = "SELECT COUNT(*) AS cnt FROM ".tablename(yx_lt_chance). $condition;
        $flags = intval(db_find($sql)['cnt']);
        return $flags;
    }

    public static function getShareMomentChance($uid,$themeid,$check_today=false)
    {
        if (empty($uid)){
            return ;
        }
        $condition = " WHERE type='share_moments' AND uid='".$uid."' AND themeid='".$themeid."' ";
        if ($check_today) {
            $today = date("Y-m-d",time());
            $condition .= " AND date="."'".$today."'";
        }
        $sql = "SELECT * AS cnt FROM ".tablename(yx_lt_chance). $condition;
        return db_find($sql);
    }

    /**
     * Desc:查询去重fromuid后的机会数
     * Author:cbw
     * Time: 2023/9/7 15:13
     * @param $uid
     * @param $type
     * @param $themeid
     * @param $check_today
     * @param $is_group
     * @return int|void
     */
    public static function getUserRecordsByTypeGroupByFromUid($uid,$type,$themeid,$check_today=false,$is_group=false)
    {
        if (empty($uid)){
            return ;
        }
        if ($type){
            $condition = " WHERE type='".$type."' AND uid=".$uid." AND themeid=".$themeid;
        }elseif ($type=='used'){
            $condition = " WHERE chance < 0 AND uid=".$uid." AND themeid=".$themeid;
        }else{
            $condition = " WHERE chance > 0  AND uid=".$uid." AND themeid=".$themeid;
        }

        if ($check_today) {
            $today = date("Y-m-d",time());
            $condition .= " AND date="."'".$today."'";
        }
        if ($is_group){
            $sql = "SELECT COUNT(distinct from_uid) AS cnt FROM ".tablename(yx_lt_chance). $condition;
        }else{
            $sql = "SELECT COUNT(*) AS cnt FROM ".tablename(yx_lt_chance). $condition;
        }
        $flags = intval(db_find($sql)['cnt']);
        return $flags;
    }

    /**
     * Desc:判断好友到访是否存在增加机会的记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/29 4:22 下午
     * @param $themeid
     * @param $uid
     * @param $fromuid
     * @return int
     */
    public static function getFriendViewChanceFlag($themeid,$uid,$fromuid,$type='friend_view')
    {
        if (empty($uid)){
            return ;
        }
        $condition = " WHERE type='$type' AND uid=".$uid." AND themeid=".$themeid." AND from_uid='$fromuid'";
        $sql = "SELECT COUNT(*) AS cnt FROM ".tablename(yx_lt_chance). $condition;
        $flags = intval(db_find($sql)['cnt']);
        return $flags;
    }
    //获取今日不同类型的定时记录
    public static function getNoReceiveTypeFlag($uid,$themeid,$type=0)
    {
        if (empty($uid)){
            return ;
        }
        $condition = " WHERE uid='{$uid}' AND themeid=$themeid  AND TO_DAYS(get_at) = TO_DAYS(NOW()) ";
        if ($type){
            $condition = " WHERE uid='{$uid}' AND themeid=$themeid AND status=$type AND TO_DAYS(get_at) = TO_DAYS(NOW()) ";
        }

        $sql = " SELECT * FROM ".tablename(yx_lt_timeset).$condition;
        return db_find($sql);
    }

    public static function getTimeFlagTotal($uid,$themeid)
    {
        $sql = " select count(*) as cnt from ".tablename(yx_lt_timeset)." where uid='{$uid}' and themeid=$themeid";
        return db_find($sql)['cnt'];
    }
    //获取最后一条待领取的计时机会
    public static function getLastWaitFlag($uid,$themeid,$status=1)
    {
        if (empty($uid)){
            return ;
        }
        if ($status) {
            $condotion = " WHERE uid='{$uid}' AND themeid=$themeid AND status=$status AND TO_DAYS(get_at) <= TO_DAYS(NOW()) ORDER BY created_at DESC";
        } else {
            $condotion = " WHERE uid='{$uid}' AND themeid=$themeid AND TO_DAYS(get_at) <= TO_DAYS(NOW())  ORDER BY created_at DESC";
        }
        $sql = " SELECT * FROM ".tablename(yx_lt_timeset).$condotion;
        return db_find($sql);
    }
    //获取无抽奖机会的提示信息
    public static function getLoseLotteryInfo($themeid)
    {
        $info = [
            'title'=>"· 温馨提示 ·",
            'desc'=>'很遗憾，您的抽奖机会已用光',
            'more_prize_title'=>'更多大奖等你来拿',
            'more_chance_tips'=>'继续抽奖'
        ];
        $content_list = [];
        $condition = " ORDER BY pr ASC LIMIT 0,5";
        $sql = " SELECT * FROM ".tablename(yx_lt_prize)." WHERE themeid=$themeid".$condition;
        $res =  db_select($sql);
        foreach ($res as $k => $v) {
            $temp = ['img'=>$v['small_img'],'name'=>$v['title']];
            array_push($content_list,$temp);
        }
        $info['more_prize_list'] = $content_list;
        return $info;
    }
    //判断是否存在幸运星
    public static function getHasLuckyStar($uid,$themeid,$t_id=0)
    {
        $has_lucky_star = false;
        $lucky_star_num = self::getLuckyStarCount($uid,$themeid,$t_id);
        if ($lucky_star_num>0) {
            $has_lucky_star = true;
        }
        return $has_lucky_star;
    }
    //获取幸运星的数量
    public static function getLuckyStarCount($uid,$themeid,$t_id=0)
    {
        if (empty($uid)){
            return ;
        }
        if ($t_id!=0){
            $condition = " WHERE themeid=$themeid AND uid='{$uid}' AND type='lucky_star' and t_id=$t_id";
        }else{
            $condition = " WHERE themeid=$themeid AND uid='{$uid}' AND type='lucky_star' ";
        }

        $sql = " SELECT COUNT(*) AS cnt FROM ".tablename(yx_lt_chance).$condition;
        return intval(db_find($sql)['cnt']);
    }
    //获得幸运星的信息
    public static function getLuckyStarInfo($uid,$theme,$config)
    {
        global $_P;
        $last_item = self::getLastLuckyItem($uid,$theme['id']);
        $username = "【".substr($theme['jubf'],0,18)."】";
        $fans = db_find ( "SELECT * FROM " . tablename ( t_scan ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$theme['id'],":uid"=>$uid));
        if (!empty($fans['fromuid'])){
            $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$theme['id'],":uid"=>$fans['fromuid']));
            if (!empty($fans['nickname'])){
                $username = "好友【".substr($fans['nickname'],0,18)."】";
            }else{
                $username = "好友【".substr($fans['username'],0,18)."】";
            }
        }
        $lucky_star_info = [
            'title'=>'幸运星',
            'icon'=>$config['yx_lt_lucky_icon'],
            'content'=>$username,
            'tips'=>'送您'.$last_item['chance'].'次抽奖机会',
            'btn_txt'=>$config['yx_lt_lucky_btm'],
        ];
        $where = ['c_id'=>$last_item['c_id']];
        $update_data = ['t_id'=>0];
        self::editChance($where,$update_data);
        return $lucky_star_info;
    }
    //获取最后一条幸运星的记录
    public static function getLastLuckyItem($uid,$themeid)
    {
        $condition = " WHERE themeid=$themeid AND uid='{$uid}' AND type='lucky_star' AND t_id=-2 ORDER BY created_at DESC limit 1";
        $sql = " SELECT *  FROM ".tablename(yx_lt_chance).$condition;
        return db_find($sql);
    }
    //插入幸运星的记录
    public static function insertLuckyItem($uid,$themeid)
    {
        $data = [
            'uid'=>$uid,
            'type'=>'lucky_star',
            'date'=>date("Y-m-d",time()),
            'chance'=>1,
            'themeid'=>$themeid,
            'from_uid'=>$uid,
            't_id'=>-2
        ];
        self::insertChance($data);
    }
    //获取活动规则
    public static function getRules($config)
    {
        $new_yx_lt_rules = [];
        if ($config['yx_lt_show_rules']==1){
            return $new_yx_lt_rules;
        }
        $yx_lt_rules = $config['yx_lt_rules'];
        $show_key = 1;
        foreach ($yx_lt_rules as $k => $v){
            if ($yx_lt_rules[$k]['rule_sort']!=0 && $yx_lt_rules[$k]['rule_content']!=''){
                $yx_lt_rules[$k]['rule_sort'] =  $show_key;
                array_push($new_yx_lt_rules,$yx_lt_rules[$k]);
                $show_key+=1;
            }
        }
        return $new_yx_lt_rules;
    }
    //获取中奖记录以及奖品信息 兑换使用
    public static function getLtFlagAndPrizeInfo($themeid,$f_id)
    {
        $sql = " SELECT a.*,b.name,b.title,b.small_img FROM ".tablename(yx_lt_flag)." AS a ".
            " LEFT JOIN ".tablename(yx_lt_prize)." AS b ON a.p_id=b.p_id".
            " WHERE a.themeid=$themeid AND a.f_id=$f_id ";
        return db_find($sql);
    }

    public static function getLtFlagAndPrizeInfoByWhere($themeid,$uid,$code,$is_code=true)
    {
        if (empty($uid)){
            return ;
        }
        if (!$is_code){
            $sql = " SELECT a.*,b.name,b.title,b.small_img,c.username,c.mobile FROM ".tablename(yx_lt_flag)." AS a ".
                " LEFT JOIN ".tablename(yx_lt_prize)." AS b ON a.p_id=b.p_id and b.themeid=$themeid".
                " LEFT JOIN ".tablename(t_fans)." AS c ON a.uid=c.uid and c.themeid=$themeid".
                " WHERE a.themeid=$themeid AND a.uid='{$uid}' and a.f_id=$code";
        }else{
            $sql = " SELECT a.*,b.name,b.title,b.small_img,c.username,c.mobile FROM ".tablename(yx_lt_flag)." AS a ".
                " LEFT JOIN ".tablename(yx_lt_prize)." AS b ON a.p_id=b.p_id and b.themeid=$themeid".
                " LEFT JOIN ".tablename(t_fans)." AS c ON a.uid=c.uid and c.themeid=$themeid".
                " WHERE a.themeid=$themeid AND a.uid='{$uid}' and a.convert_code='".$code."'";
        }
        return db_find($sql);
    }
    //更新用户未兑换的全部失效
    public static function editUserLtFlagLose($uid,$themeid,$p_id,$f_id)
    {
        $sql = " UPDATE ".tablename(yx_lt_flag)." SET status=2 WHERE status!=4 AND themeid=$themeid AND uid='{$uid}'";
        return \think\Db::execute($sql);
    }
    //获取今日指定的红包的发放数量
    public static function getRedPackageSendNum($themeid,$p_id)
    {
        $sql = "SELECT COUNT(*) AS cnt FROM ".tablename(yx_lt_rp_flag).
            " WHERE themeid=$themeid AND p_id=$p_id AND TO_DAYS(created_at) = TO_DAYS(NOW())";
        return db_find($sql)['cnt'];
    }

    //获取今日指定的红包的发放金额
    public static function getRedPackageSendAmount($themeid,$p_id)
    {
        $sql = "SELECT SUM(amount) as send_total FROM ".tablename(yx_lt_rp_flag).
            " WHERE themeid=$themeid AND p_id=$p_id AND TO_DAYS(created_at) = TO_DAYS(NOW())";
        return db_find($sql)['send_total'];
    }

    /**
     * Desc:获取红包发放的金额 通过is_today 区分今日和全部
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/29 2:30 下午
     * @param $themeid  --活动id int
     * @param false $is_today 只查询今日 bool
     * @return mixed
     */
    public static function getRedPackageTotal($themeid,$is_today=false)
    {
        if (!$is_today) {
            $sql = " SELECT SUM(amount) as send_total FROM ".tablename(yx_lt_rp_flag).
                " WHERE themeid=$themeid ";
        } else {
            $sql = " SELECT SUM(amount) as send_total FROM ".tablename(yx_lt_rp_flag).
                " WHERE themeid=$themeid AND TO_DAYS(created_at) = TO_DAYS(NOW())";
        }
        return db_find($sql)['send_total'];
    }

    /**
     * Desc:判断能否发送红包
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/29 2:50 下午
     * @param $send_total
     * @param $config
     * @param $themeid
     * @param int $workerid
     * @param false $check_worker
     * @return bool
     */
    public static function checkRedPackageLimit($send_total,$get_lt,$rand_amount,$config,$themeid,$workerid=0,$check_worker=false)
    {
        if (!$config || !$themeid) {
            return false;
        }
        if ($check_worker) {
            $worker=db_find("SELECT * FROM ".tablename(t_worker)." WHERE uid = '{$workerid}'");
            if (!$worker) {
                return false;
            }
        }
        $today_num = (int)$send_total+1;
        $today_limit_num = (int)$get_lt['red_envelopes_day_qty'];

        $total_limit = $config['red_envelopes_total_amount'];
        $today_limit = $config['red_envelopes_day_amount'];

        $total_amount = self::getRedPackageTotal($themeid);
        $today_amount = self::getRedPackageTotal($themeid,true);

        $new_total_amount = $total_amount+$rand_amount;
        $new_today_amount = $today_amount+$rand_amount;
        if ($new_total_amount <= $total_limit) {
            if ($new_today_amount <= $today_limit) {
                if ($today_num<=$today_limit_num){
                    return true;
                }
                return false;
            }
            return false;
        } else {
            return false;
        }
    }

    /**
     * Desc:红包提现
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/3/29 3:31 下午
     * @param $amount
     * @param $themeid
     * @param $fans
     * @param $ordersn
     * @param $fromuid
     * @return mixed
     */
    public static function UserWithdraw($amount,$themeid,$fans,$ordersn,$fromuid)
    {
        $data = array(
            'uniacid'    => $fans['uniacid'],
            'themeid'    => $themeid,
            'recordid'   => -13,
            'ordersn'    => $ordersn,
            'type'       => 13,
            'openid'     => $fans['openid'],
            'uid'     => $fans['uid'],
            'addtime'    => TIMESTAMP,
            'fee'        => $amount,
            'fopenid'    => $fans['fopenid'],
            'fromuid'    => $fromuid,
            'openid_old'     => $fans['openid_old'],
            'uid_old'     => $fans['uid_old'],
            'fopenid_old'    => $fans['fopenid_old'],
            'fromuid_old'    => $fans['fromuid_old'],
            'status'     =>0,
        );
        return Comm::add_share_comm($data);
    }

    public static function getUserWithDrawAmount($themeid,$uid)
    {
        $sql = " SELECT SUM(amount) as send_total FROM ".tablename(yx_lt_rp_flag).
            " WHERE themeid=$themeid and uid='{$uid}'";
        return db_find($sql)['send_total'];
    }

    //定单中关联用户的中奖信息
    public static function getUserLotteryInfo($themeid,$fans,$type=1)
    {
        $user_flag_arr = [];
        $prize_list = db_getall(yx_lt_prize,['themeid'=>$themeid]);

        $user_flag = self::getUserPrizeList($themeid,$fans['uid']);
        if ($user_flag){
            foreach ($user_flag as $k => $v){
                foreach ($prize_list as $key => $val){
                    if ($val['p_id']==$v['p_id']){
                        if (count($user_flag_arr)>0){
                            $has_item = false;
                            foreach ($user_flag_arr as $kk => $vv){
                                if ($vv['p_id']==$v['p_id']){
                                    $has_item = true;
                                    $user_flag_arr[$kk]['total'] +=1;
                                }
                            }
                            if (!$has_item){
                                array_push($user_flag_arr,['p_id'=>$val['p_id'],'name'=>$val['name'],'total'=>1,'title'=>$val['title']]);
                            }
                        }else{
                            array_push($user_flag_arr,['p_id'=>$val['p_id'],'name'=>$val['name'],'total'=>1,'title'=>$val['title']]);
                        }
                    }
                }
            }
        }

        if ($type==1){
            return $user_flag_arr;
        }
        $tmp_str = "";
        if ($user_flag_arr){
            foreach ($user_flag_arr as $dd=> $ff){
                $tmp_str.= '['.$ff['title'].']'.'*'.$ff['total'].';';
            }
        }
        return $tmp_str;
    }

    //获取上架、中奖概率大于0的实物奖项
    public static function getCanEditList($themeid)
    {
        $sql = " select * from ".tablename(yx_lt_prize)." where themeid=$themeid and type='default' and pr>=0 and status=1";
        return db_select($sql);
    }

    /**
     * Desc:根据当前配置抽奖机会 生成抽奖规则
     * Author:cbw
     * Time: 2023/9/24 10:27
     * @param $params
     * @return array
     */
    public static function productYxLtRule($params)
    {
        $yx_lt_rules = [];
        $tmp_rule_sort = 1;
        if (is_null($params['yx_lt_rule_sort']) && is_null($params['yx_lt_rule_content'])){
            //首次提交 未填写
            if ($params['yx_lt_no_sign_up']){
                $tmp_rule_content = '首次进入，可获得#num次机会.';
                $yx_lt_rules[] = ['id'=>'yx_lt_no_sign_up','rule_content' => str_replace('#num', $params['yx_lt_no_sign_up'], $tmp_rule_content), 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }else{
                $yx_lt_rules[] = ['id'=>'yx_lt_no_sign_up','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
            }
            if ($params['yx_lt_self_order']){
                $tmp_rule_content = '支付成功，可获得#num次机会.';
                $yx_lt_rules[] = ['id'=>'yx_lt_self_order','rule_content' => str_replace('#num', $params['yx_lt_self_order'], $tmp_rule_content), 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }else{
                $yx_lt_rules[] = ['id'=>'yx_lt_self_order','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
            }
            if ($params['yx_lt_friend_order']){
                $tmp_rule_content = '成功推荐一位好友支付成功，可获得#num次机会.';
                if($params['yx_lt_main_order']){
                    $tmp_rule_content = '支付成功后，成功推荐一位好友支付成功，可获得#num次机会.';
                }
                $yx_lt_rules[] = ['id'=>'yx_lt_friend_order','rule_content' => str_replace('#num', $params['yx_lt_friend_order'], $tmp_rule_content), 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }else{
                $yx_lt_rules[] = ['id'=>'yx_lt_friend_order','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
            }
            if ($params['yx_lt_first_share_moment'] || $params['yx_lt_second_share_moment'] || $params['yx_lt_third_share_moment']){
                $tmp_rule_content = '';
                if ($params['yx_lt_share_moment_user_type']){
                    $tmp_rule_content = '支付成功后,';
                }
                if($params['yx_lt_first_share_moment']){
                    $tmp_rule_content .= '第一天分享朋友圈，可获得#num次机会';
                    $format_tmp_pre = str_replace('#num',$params['yx_lt_first_share_moment'],$tmp_rule_content);
                }
                if($params['yx_lt_second_share_moment']){
                    $tmp_rule_content .= '；第二天分享朋友圈，可获得#num2次机会';
                    $format_tmp_pre = str_replace('#num2',$params['yx_lt_second_share_moment'],$tmp_rule_content);
                }
                if($params['yx_lt_third_share_moment']){
                    $tmp_rule_content .= '；第三天分享朋友圈，可获得#num3次机会';
                    $format_tmp_pre = str_replace('#num3',$params['yx_lt_third_share_moment'],$tmp_rule_content);
                }
                $yx_lt_rules[] = ['id'=>'yx_lt_first_share_moment','rule_content' => $format_tmp_pre, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }else{
                $yx_lt_rules[] = ['id'=>'yx_lt_first_share_moment','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
            }
            if ($params['yx_lt_friend_view']){
                $tmp_pre  = '';
                if ($params['yx_lt_view_user_type']){
                    $tmp_pre .= '支付成功后,';
                }
                $tmp_rule_content = $tmp_pre;
                $tmp_rule_content .= '每邀请#num位好友打开自己活动链接，可获得1次机会';
                if ($params['yx_lt_friend_view_limit']){
                    $tmp_rule_content.= ',最多可获得#max次机会.';
                }
                $format_tmp_pre = str_replace('#num',$params['yx_lt_friend_view'],$tmp_rule_content);
                $format_tmp_pre = str_replace('#max',$params['yx_lt_friend_view_limit'],$format_tmp_pre);
                $yx_lt_rules[] = ['id'=>'yx_lt_friend_view','rule_content' => $format_tmp_pre, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }else{
                $yx_lt_rules[] = ['id'=>'yx_lt_friend_view','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
            }
            if ($params['yx_lt_friend_help']){
                $tmp_pre = '';
                if ($params['yx_lt_help_user_type']){
                    $tmp_pre .= '支付成功后,';
                }
                $tmp_rule_content = $tmp_pre;
                $tmp_rule_content .= '每邀请#num位好友助力，可获得1次机会';
                if ($params['yx_lt_friend_help_limit']){
                    $tmp_rule_content.= ',最多可获得#max次机会.';
                }
                $format_tmp_pre = str_replace('#num',$params['yx_lt_friend_help'],$tmp_rule_content);
                $format_tmp_pre = str_replace('#max',$params['yx_lt_friend_help_limit'],$format_tmp_pre);
                $yx_lt_rules[] = ['id'=>'yx_lt_friend_help','rule_content' => $format_tmp_pre, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }else{
                $yx_lt_rules[] = ['id'=>'yx_lt_friend_help','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
            }
            if ($params['yx_lt_timeset']){
                $tmp_pre = '';
                if ($params['yx_lt_timeset_user_type']){
                    $tmp_pre .= '支付成功后,';
                }
                $tmp_rule_content = $tmp_pre;
                $tmp_rule_content .= '每日首次登陆#num小时后，可获得1次机会';
                if ($params['yx_lt_timeset_limit']){
                    $tmp_rule_content.= ',最多可获得#max次机会.';
                }
                $format_tmp_pre = str_replace('#num',$params['yx_lt_timeset'],$tmp_rule_content);
                $format_tmp_pre = str_replace('#max',$params['yx_lt_timeset_limit'],$format_tmp_pre);
                $yx_lt_rules[] = ['id'=>'yx_lt_timeset','rule_content' => $format_tmp_pre, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }else{
                $yx_lt_rules[] = ['id'=>'yx_lt_timeset','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
            }
            if ($params['yx_lt_chance_limit']){
                $tmp_rule_content = '最多可获得#max次机会.';
                $format_tmp_pre = str_replace('#max',$params['yx_lt_chance_limit'],$tmp_rule_content);
                $yx_lt_rules[] = ['id'=>'yx_lt_chance_limit','rule_content' => $format_tmp_pre, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                $tmp_rule_sort+=1;
            }
//            $tmp_rule_content = '仅限本地0-12岁宝妈/孕妈参与';
//            $yx_lt_rules[] = ['id'=>'','rule_content' => $tmp_rule_content, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
//            $tmp_rule_sort+=1;
            $tmp_rule_content = '奖品仅限本人进店领取，不代领，不邮寄！';
            $yx_lt_rules[] = ['id'=>'','rule_content' => $tmp_rule_content, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
            $tmp_rule_sort+=1;
            $tmp_rule_content = '加客服微信登记中奖奖品，预约领取时间';
            $yx_lt_rules[] = ['id'=>'','rule_content' => $tmp_rule_content, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
            $tmp_rule_sort+=1;
        }else{
            foreach ($params['yx_lt_rule_content'] as $k => $v){
                $tmp_format_content = $params['yx_lt_format_content'][$k];
                $tmp_id = $params['yx_lt_rule_id'][$k];
                $tmp_rule_sort = $params['yx_lt_rule_sort'][$k]?intval($params['yx_lt_rule_sort'][$k]):$tmp_rule_sort;
                if ($tmp_id=='yx_lt_no_sign_up'){
                    if ($params['yx_lt_no_sign_up']){
                        if (!$tmp_format_content){
                            $tmp_rule_content = '首次进入，可获得#num次机会.';
                            $yx_lt_rules[] = ['id'=>'yx_lt_no_sign_up','rule_content' => str_replace('#num', $params['yx_lt_no_sign_up'], $tmp_rule_content), 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if(strpos($tmp_format_content,'#num')!==false){
                                $yx_lt_rules[] = ['id'=>'yx_lt_no_sign_up','rule_content' => str_replace('#num', $params['yx_lt_no_sign_up'], $tmp_format_content), 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_no_sign_up','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_no_sign_up','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                elseif ($tmp_id=='yx_lt_self_order'){
                    if ($params['yx_lt_self_order']){
                        if (!$tmp_format_content){
                            $tmp_rule_content = '支付成功，可获得#num次机会.';
                            $yx_lt_rules[] = ['id'=>'yx_lt_self_order','rule_content' => str_replace('#num', $params['yx_lt_self_order'], $tmp_rule_content), 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if(strpos($tmp_format_content,'#num')!==false){
                                $yx_lt_rules[] = ['id'=>'yx_lt_self_order','rule_content' => str_replace('#num', $params['yx_lt_self_order'], $tmp_format_content), 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_self_order','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_self_order','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                elseif ($tmp_id=='yx_lt_friend_order'){
                    if ($params['yx_lt_friend_order']){
                        if (!$tmp_format_content){
                            $tmp_rule_content = '成功推荐一位好友支付成功，可获得#num次机会.';
                            if($params['yx_lt_main_order']){
                                $tmp_rule_content = '支付成功后，成功推荐一位好友支付成功，可获得#num次机会.';
                            }
                            $yx_lt_rules[] = ['id'=>'yx_lt_friend_order','rule_content' => str_replace('#num', $params['yx_lt_friend_order'], $tmp_rule_content), 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if (strpos($tmp_format_content,'支付成功后，')!==false){
                                if (!$params['yx_lt_main_order']){
                                    $tmp_format_content = str_replace('支付成功后，', '', $tmp_format_content);
                                }
                            }else{
                                if ($params['yx_lt_main_order']){
                                    $tmp_format_content = '支付成功后，'.$tmp_format_content;
                                }
                            }
                            if(strpos($tmp_format_content,'#num')!==false){
                                $yx_lt_rules[] = ['id'=>'yx_lt_friend_order','rule_content' => str_replace('#num', $params['yx_lt_friend_order'], $tmp_format_content), 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_friend_order','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_friend_order','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                elseif ($tmp_id=='yx_lt_first_share_moment'){
                    if ($params['yx_lt_first_share_moment'] || $params['yx_lt_second_share_moment'] || $params['yx_lt_third_share_moment']){
                        if (!$tmp_format_content){
                            $tmp_pre = '';
                            if ($params['yx_lt_share_moment_user_type']){
                                $tmp_pre .= '支付成功后,';
                            }
                            $tmp_rule_content = $tmp_pre;
                            if($params['yx_lt_first_share_moment']){
                                $tmp_rule_content .= '第一天分享朋友圈，可获得#num次机会';
                                $tmp = str_replace('#num', $params['yx_lt_first_share_moment'], $tmp_rule_content);
                            }
                            if($params['yx_lt_second_share_moment']){
                                if ($params['yx_lt_first_share_moment']){
                                    $tmp_rule_content .= '；';
                                }
                                $tmp_rule_content .= '第二天分享朋友圈，可获得#num2次机会';
                                $tmp .= $tmp_rule_content;
                                $tmp = str_replace('#num2', $params['yx_lt_second_share_moment'], $tmp);
                            }
                            if($params['yx_lt_third_share_moment']){
                                if ($params['yx_lt_second_share_moment']){
                                    $tmp_rule_content .= '；';
                                }
                                $tmp_rule_content .= '第三天分享朋友圈，可获得#num3次机会';
                                $tmp .= $tmp_rule_content;
                                $tmp .= str_replace('#num3', $params['yx_lt_third_share_moment'], $tmp);
                            }
                            $yx_lt_rules[] = ['id'=>'yx_lt_self_order','rule_content' => $tmp, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if (strpos($tmp_format_content,'支付成功后,')!==false){
                                if (!$params['yx_lt_share_moment_user_type']){
                                    $tmp_format_content = str_replace('支付成功后,', '', $tmp_format_content);
                                }
                            }else{
                                if ($params['yx_lt_share_moment_user_type']){
                                    $tmp_format_content = '支付成功后,'.$tmp_format_content;
                                }
                            }
                            if(strpos($tmp_format_content,'#num')!==false){
                                $tmp = str_replace('#num3', $params['yx_lt_third_share_moment'], $tmp_format_content);
                                $tmp = str_replace('#num2', $params['yx_lt_second_share_moment'], $tmp);
                                $tmp = str_replace('#num', $params['yx_lt_first_share_moment'], $tmp);
                                $yx_lt_rules[] = ['id'=>'yx_lt_first_share_moment','rule_content' => $tmp, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_first_share_moment','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_first_share_moment','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                elseif ($tmp_id=='yx_lt_friend_view'){
                    if ($params['yx_lt_friend_view']){
                        if (!$tmp_format_content){
                            $tmp_pre = '';
                            if ($params['yx_lt_view_user_type']){
                                $tmp_pre .= '支付成功后,';
                            }
                            $tmp_rule_content = $tmp_pre;
                            $tmp_rule_content .= '每邀请#num位好友打开自己活动链接，可获得1次机会';
                            if ($params['yx_lt_friend_view_limit']){
                                $tmp_rule_content.= ',最多可获得#max次机会.';
                            }
                            $tmp_str = str_replace('#num', $params['yx_lt_friend_view'], $tmp_rule_content);
                            $tmp_str = str_replace('#max', $params['yx_lt_friend_view_limit'], $tmp_str);
                            $yx_lt_rules[] = ['id'=>'yx_lt_friend_view','rule_content' => $tmp_str, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if (strpos($tmp_format_content,'支付成功后,')!==false){
                                if (!$params['yx_lt_view_user_type']){
                                    $tmp_format_content = str_replace('支付成功后,', '', $tmp_format_content);
                                }
                            }else{
                                if ($params['yx_lt_view_user_type']){
                                    $tmp_format_content = '支付成功后,'.$tmp_format_content;
                                }
                            }
                            if(strpos($tmp_format_content,'#num')!==false){
                                $tmp_str = str_replace('#num', $params['yx_lt_friend_view'], $tmp_format_content);
                                $tmp_str = str_replace('#max', $params['yx_lt_friend_view_limit'], $tmp_str);
                                $yx_lt_rules[] = ['id'=>'yx_lt_friend_view','rule_content' => $tmp_str, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_friend_view','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_friend_view','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                elseif ($tmp_id=='yx_lt_friend_help'){
                    if ($params['yx_lt_friend_help']){
                        if (!$tmp_format_content){
                            $tmp_pre = '';
                            if ($params['yx_lt_help_user_type']){
                                $tmp_pre .= '支付成功后,';
                            }
                            $tmp_rule_content = $tmp_pre;
                            $tmp_rule_content .= '每邀请#num位好友助力，可获得1次机会';
                            if ($params['yx_lt_friend_help_limit']){
                                $tmp_rule_content.= ',最多可获得#max次机会.';
                            }
                            $tmp_str = str_replace('#num', $params['yx_lt_friend_help'], $tmp_rule_content);
                            $tmp_str = str_replace('#max', $params['yx_lt_friend_help_limit'], $tmp_str);
                            $yx_lt_rules[] = ['id'=>'yx_lt_friend_help','rule_content' => $tmp_str, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if (strpos($tmp_format_content,'支付成功后,')!==false){
                                if (!$params['yx_lt_help_user_type']){
                                    $tmp_format_content = str_replace('支付成功后,', '', $tmp_format_content);
                                }
                            }else{
                                if ($params['yx_lt_help_user_type']){
                                    $tmp_format_content = '支付成功后,'.$tmp_format_content;
                                }
                            }
                            if(strpos($tmp_format_content,'#num')!==false){
                                $tmp_str = str_replace('#num', $params['yx_lt_friend_help'], $tmp_format_content);
                                $tmp_str = str_replace('#max', $params['yx_lt_friend_help_limit'], $tmp_str);
                                $yx_lt_rules[] = ['id'=>'yx_lt_friend_help','rule_content' => $tmp_str, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_friend_help','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_friend_help','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                elseif ($tmp_id=='yx_lt_timeset'){
                    if ($params['yx_lt_timeset']){
                        if (!$tmp_format_content){
                            $tmp_pre = '';
                            if ($params['yx_lt_timeset_user_type']){
                                $tmp_pre = '支付成功后,';
                            }
                            $tmp_rule_content = $tmp_pre;
                            $tmp_rule_content .= '每日首次登陆#num小时后，可获得1次机会';
                            if ($params['yx_lt_timeset_limit']){
                                $tmp_rule_content.= ',最多可获得#max次机会.';
                            }
                            $tmp_str = str_replace('#num', $params['yx_lt_timeset'], $tmp_rule_content);
                            $tmp_str = str_replace('#max', $params['yx_lt_timeset_limit'], $tmp_str);
                            $yx_lt_rules[] = ['id'=>'yx_lt_timeset','rule_content' => $tmp_str, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if (strpos($tmp_format_content,'支付成功后,')!==false){
                                if (!$params['yx_lt_timeset_user_type']){
                                    $tmp_format_content = str_replace('支付成功后,', '', $tmp_format_content);
                                }
                            }else{
                                if ($params['yx_lt_timeset_user_type']){
                                    $tmp_format_content = '支付成功后,'.$tmp_format_content;
                                }
                            }
                            if(strpos($tmp_format_content,'#num')!==false){
                                $tmp_str = str_replace('#num', $params['yx_lt_timeset'], $tmp_format_content);
                                $tmp_str = str_replace('#max', $params['yx_lt_timeset_limit'], $tmp_str);
                                $yx_lt_rules[] = ['id'=>'yx_lt_timeset','rule_content' => $tmp_str, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_timeset','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_timeset','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                elseif ($tmp_id=='yx_lt_chance_limit'){
                    if ($params['yx_lt_chance_limit']){
                        if (!$tmp_format_content){
                            $tmp_rule_content = '最多可获得#max次机会.';
                            $tmp_str = str_replace('#max', $params['yx_lt_chance_limit'], $tmp_rule_content);
                            $yx_lt_rules[] = ['id'=>'yx_lt_chance_limit','rule_content' => $tmp_str, 'format_content' => $tmp_rule_content, 'rule_sort' => $tmp_rule_sort];
                        }else{
                            if(strpos($tmp_format_content,'#max')!==false){
                                $tmp_str = str_replace('#max', $params['yx_lt_chance_limit'], $tmp_format_content);
                                $yx_lt_rules[] = ['id'=>'yx_lt_chance_limit','rule_content' => $tmp_str, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }else{
                                $yx_lt_rules[] = ['id'=>'yx_lt_chance_limit','rule_content' => $tmp_format_content, 'format_content' => $tmp_format_content, 'rule_sort' => $tmp_rule_sort];
                            }
                        }
                    }else{
                        $yx_lt_rules[] = ['id'=>'yx_lt_chance_limit','rule_content' => '', 'format_content' => '', 'rule_sort' => $tmp_rule_sort];
                    }
                }
                else{
                    if ($tmp_format_content){
                        $tmp_rule_sort = $params['yx_lt_rule_sort'][$k];
                        if ($tmp_format_content){
                            $v = $tmp_format_content;
                        }
                        $yx_lt_rules[] = ['id'=>'','rule_content' => $v, 'format_content' => $v, 'rule_sort' => $tmp_rule_sort];
                        $tmp_rule_sort+=1;
                    }else{
                        $yx_lt_rules[] = ['id'=>'','rule_content' => '', 'format_content' => '', 'rule_sort' => 0];
                    }
                }
            }
        }
        array_multisort(array_column($yx_lt_rules,'rule_sort'),SORT_ASC,$yx_lt_rules);
        return $yx_lt_rules;
    }

    public static function getLotteryUserList($system,$config,$themeid,$page_start=0,$page_size=0,$search,$count = false)
    {
        if($system['is_multiple_merchants'] && $config['showshop']==0){
            $company_list = db_select("SELECT id,name FROM ".tablename (t_shangjia),array(),'id');
        }else{
            $company_list = array();
        }
        //查询团队
        $team_list =  db_select("SELECT id,company,name FROM ".tablename (t_team),array(),'id');
        $worker_list =  db_select("SELECT id,themeid,uid,username,company,team,superior,level,concat(themeid,'_',uid) as theme_uid FROM ".tablename ( t_worker)." WHERE  themeid = {$themeid}" ,array(),'theme_uid');

        $type = $search['type'];
        $condition = "";
        $having = "";
        switch($type){
            case 1:      //已支付
                $condition .= " and r.status = 1";
                break;
            case 2:     //未支付
                $condition .= " and (r.status = 0 or r.status IS NULL)";
                break;
            case 3:     //从未抽过
                $having = " HAVING get_num>0 and use_num>0 ";
                break;
            case 4:     //已抽过
                $having = " HAVING use_num>0";
                break;
        }

        $chance_type = $search['chance_type'];
        $chance_range = $search['chance_range'];
        $chance_num = isset($search['chance_num'])?$search['chance_num']:0;
        $range = '';
        switch ($chance_range) {
            case 1:
                $range = '=';
                break;
            case 2:
                $range = '>';
               break;
            case 3:
                $range = '<';
                break;
            case 4:
                $range = '>=';
                break;
            case 5:
                $range = '<=';
            break;
        }

        switch($chance_type){
            case 1:
                $having = " HAVING get_num{$range}{$chance_num}";
                break;
            case 2:
                $having = " HAVING use_num{$range}{$chance_num}";
                break;
            case 3:
                $condition .= " and f.jihui{$range}{$chance_num}";
                break;
        }

        $workerid = isset($search['workerid'])?intval($search['workerid']):0;
        if($workerid){
            $condition .= " and (f.workerid = {$workerid} or r.workerid = {$workerid})";
        }

        $search_keyword = $search['search_data'];
        if ($search_keyword){
            $condition .= " and f.uid ='{$search_keyword}' or f.nickname like '".$search_keyword."'"." or f.mobile like '".$search_keyword."' " ." or f.username like '".$search_keyword."' ";
        }

        $sql = " from ".tablename(yx_lt_chance)." as c 
                 left join " .tablename(t_fans)." as f on f.uid=c.uid and f.themeid=$themeid
                 LEFT JOIN ".tablename(t_record)." AS r ON c.uid=r.uid and r.themeid=$themeid
                 WHERE c.themeid=$themeid ";

        if ($count){
             $count_sql ="select f.uid,
                          sum(case when c.chance>0 then c.chance else 0 end) as get_num,
                          sum(case when c.chance<0 then c.chance*-1 else 0 end) as use_num          
                    ".$sql.$condition .'  group by c.uid '.$having;
             return count(db_select($count_sql));
        }else{
            $limit = '';
            if ($page_size) {
                $limit = " LIMIT ".$page_start.",".$page_size;
            }
            $prize_array = db_getall(yx_lt_prize,  ['themeid' => $themeid],['p_id','title'],'p_id');

            $list_sql = " select f.id as fanid,f.uid,f.nickname,f.avatar,f.username,f.mobile,f.jihui,f.workerid,r.status as pay_status,r.workerid as pay_workerid,
                          sum(case when c.chance>0 then c.chance else 0 end) as get_num,
                          sum(case when c.chance<0 then c.chance*-1 else 0 end) as use_num          
                    ".$sql.$condition .'  group by c.uid '.$having.' ORDER BY c.uid asc '.$limit;
            $all_list = db_select($list_sql,array(),'uid');

            if($all_list){
                $uids_array = array_keys($all_list);
                $uids = implode(',',$uids_array);
                $uids = rtrim($uids,",");
                $flag_where = " themeid={$themeid} ";
                if($page_size){
                    $flag_where .= " and uid in ({$uids})";
                }
                $flag_sql = " select  uid,group_concat(p_id) as prod_id  from ".tablename(yx_lt_flag)."  where ".$flag_where." group by uid order by uid asc";
                $flag_list = db_select($flag_sql,array(),'uid');

//                if ($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime']) {
//                    $userlist = Fans::getWeiBukuanList($config,$themeid);
//                }

//                $record_sql=" select id,uid,themeid,type,status,addtime,workerid  from ".tablename(t_record)."  where  id in (select max(id) from ".tablename(t_record)." group by uid)";
//                $record_list = db_select($record_sql,array(),'uid');
            }

            foreach ($all_list as $key=>$val){
                $prize_name = '';
                if($flag_list[$key]){
                    $flag = $flag_list[$key];
                    $prod_arr = explode(',',$flag['prod_id']);
                    foreach ($prod_arr as $k2=>$v2){
                        $prod = $prize_array[$v2];
                        if($prod){
                            $prize_name.= $prize_name?' | '.$prod['title']:$prod['title'];
                        }
                    }
                }
               $all_list[$key]['prize_name'] = $prize_name;
//               $record_info = $record_list[$key];
//               if($record_info){
//                   $recordid = $record_info['id'];
//                   $status = $record_info['status'];
//                   $addtime = $record_info['addtime'];
//                   $type = $record_info['type'];
//                   $pay_status = getPayStatus($config,$themeid,$userlist,$recordid,$status,$addtime,$type);
//                   $all_list[$key]['pay_status'] = $pay_status['txt'];
//                   $all_list[$key]['pay_class'] = $pay_status['class'];
//                   $val['workerid'] = $record_info['workerid'];
//               }

                $val['workerid'] = $val['pay_workerid']?$val['pay_workerid']:$val['workerid'];
                $worker = '';
                if($val['workerid']){
                    $worker_info = $worker_list[$themeid.'_'.$val['workerid']];
                    if($worker_info){
                        $worker .= $worker_info['username'].' ';
                    }

                    if($team_list[$worker_info['team']]){
                        $team_info = $team_list[$worker_info['team']];
                        $worker .= $team_info['name'].' ';
                    }

                    if($company_list[$worker_info['company']]){
                        $company_info = $company_list[$worker_info['company']];
                        $worker .= $company_info['name'];
                    }
               }

               $all_list[$key]['workerid']  =  $val['workerid'] ;
               $all_list[$key]['worker']  = $worker;
               if($val['pay_status']==1){
                    $all_list[$key]['pay_class'] = 'success';
                    $all_list[$key]['pay_txt'] = '已支付';
               }elseif ($val['pay_status']==3){
                    $all_list[$key]['pay_class'] = 'info';
                    $all_list[$key]['pay_txt'] = '线下订单';
               }else{
                    $all_list[$key]['pay_class'] = 'warning';
                    $all_list[$key]['pay_txt'] = '未支付';
               }
            }
            return  $all_list;
        }
    }

    public static function getPrizeRes($list){
        $get_lt = [];
        $probability = 0;
        foreach ($list as $index=>$item){
            $probability +=$item['pr'];
        }
        if ($probability==0 ){
            return ['error'=>1,'msg'=>'中奖率为0'];
        }
        $arr = $list;
        $arr = Ad::arraySort($arr,'pr');
        $beishu = 100/$probability;
        $rand = rand(0,10000)/100;
        $now = 0;
        foreach ($arr as $index=>$value) {
            $now =$now + ($value['pr']*$beishu);
            if ($rand<$now || $index==count($arr)-1){
                $get_lt = $arr[$index];
                break;
            }
        }
        if (!$get_lt){
            return ['error'=>2,'msg'=>'无中奖奖品'];
        }
        return ['error'=>0,'msg'=>'success','get_lt'=>$get_lt];
    }

    /**
     * Desc:获取用户可增加的机会数
     * Author:cbw
     * Time: 2023/10/14 13:13
     * @param $config
     * @param $themeid
     * @param $fans
     * @return mixed
     */
    public static function getUserCanAddChance($config,$themeid,$fans)
    {
        $change_limit = $config['yx_lt_chance_limit'];
        $remain_chance_num = $fans['jihui'];
        $sql = " select count(*) as cnt from ".tablename(yx_lt_chance)." where themeid=$themeid and uid='{$fans['uid']}' and chance<0 and type='system'";
        $used_chance_num =  db_find($sql)['cnt'];
        $user_get_chance_num = $remain_chance_num+$used_chance_num;
        return max(0,($change_limit-$user_get_chance_num));
    }

    /**
     * Desc:触发定时判断更新奖品组
     * Author:cbw
     * Time: 2023/11/29 17:32
     * @param $themeid
     */
    public static function setTimeChangePrizeGroupStatus($themeid)
    {
        if (MODULE_NAME=='ew68743' || MODULE_NAME=='tp0210' || MODULE_NAME=='yx18900'){
            if($themeid <= 0){
                $themeid = Theme::getDefaultThemenew();
            }
            $sql = " SELECT COUNT(*) AS cnt FROM " .tablename(yx_lt_prize)." WHERE themeid='$themeid'";
            $prize_total =  db_find($sql)['cnt'];
            if (count($prize_total)!=16){
                yxlog('九宫格奖品数量不足16个无法进行指定操作','开发调试');
            }else{
                $tmp_item = db_get(yx_lt_prize,['themeid'=>$themeid]);
                $tmp_updated_at = strtotime($tmp_item['updated_at']);
                if (time()>$tmp_updated_at && (time()-$tmp_updated_at>60)){
                    //控制每5分钟切换奖品
                    $i = date('i');
                    if ($i%5==0){
                        self::changePrizeGroup($themeid);
                    }
                }
            }
        }
    }

    /**
     * Desc:更换奖品组
     * Author:cbw
     * Time: 2023/11/29 17:33
     * @param $themeid
     */
    public static function changePrizeGroup($themeid)
    {
        //判断最后一个奖品的状态
        $last_prize_item_sql = " select * from ".tablename(yx_lt_prize)." where themeid=$themeid and p_id>0 order by p_id desc limit 1";
        $last_prize_item = db_find($last_prize_item_sql);
        $updated_at = date("Y-m-d H:i:s",time());
        if ($last_prize_item){
            if ($last_prize_item['status']==1){
                //上架前8个  下架后8个
                $sql1 = " update ".tablename(yx_lt_prize)." set status=1,updated_at='$updated_at' order by p_id asc limit 8;".
                    " update ".tablename(yx_lt_prize)." set status=2,updated_at='$updated_at' order by p_id desc limit 8;";
            }elseif ($last_prize_item['status']==2){
                //上架后8个  下架前8个
                $sql1 = " update ".tablename(yx_lt_prize)." set status=1,updated_at='$updated_at' order by p_id desc limit 8;".
                    " update ".tablename(yx_lt_prize)." set status=2,updated_at='$updated_at' order by p_id asc limit 8;";
            }
        }
        db_run($sql1);
        yxlog('九宫格奖品组更换成功','开发调试');
    }
}